Page Menu
Home
Phabricator
Search
Configure Global Search
Log In
Files
F14865067
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Flag For Later
Size
61 KB
Subscribers
None
View Options
diff --git a/electrum/electrumabc/mnemo.py b/electrum/electrumabc/mnemo.py
index 2288f0be7..723cd7cb5 100644
--- a/electrum/electrumabc/mnemo.py
+++ b/electrum/electrumabc/mnemo.py
@@ -1,492 +1,367 @@
#
# Electrum ABC - lightweight eCash client
# Copyright (C) 2020 The Electrum ABC developers
# Copyright (C) 2014 Thomas Voegtlin
#
# Electron Cash - lightweight Bitcoin Cash client
# Copyright (C) 2020 The Electron Cash Developers
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import hashlib
import math
-import os
-import pkgutil
-import string
-import unicodedata
-import weakref
from enum import IntEnum, auto, unique
-from typing import Dict, List, Optional, Set, Tuple, Union
+from typing import List, Optional, Set, Tuple, Union
import mnemonic
from . import old_mnemonic, version
from .bitcoin import hmac_sha_512
from .printerror import PrintError
from .util import randrange
-
-# http://www.asahi-net.or.jp/~ax2s-kmtn/ref/unicode/e_asia.html
-CJK_INTERVALS = [
- (0x4E00, 0x9FFF, "CJK Unified Ideographs"),
- (0x3400, 0x4DBF, "CJK Unified Ideographs Extension A"),
- (0x20000, 0x2A6DF, "CJK Unified Ideographs Extension B"),
- (0x2A700, 0x2B73F, "CJK Unified Ideographs Extension C"),
- (0x2B740, 0x2B81F, "CJK Unified Ideographs Extension D"),
- (0xF900, 0xFAFF, "CJK Compatibility Ideographs"),
- (0x2F800, 0x2FA1D, "CJK Compatibility Ideographs Supplement"),
- (0x3190, 0x319F, "Kanbun"),
- (0x2E80, 0x2EFF, "CJK Radicals Supplement"),
- (0x2F00, 0x2FDF, "CJK Radicals"),
- (0x31C0, 0x31EF, "CJK Strokes"),
- (0x2FF0, 0x2FFF, "Ideographic Description Characters"),
- (0xE0100, 0xE01EF, "Variation Selectors Supplement"),
- (0x3100, 0x312F, "Bopomofo"),
- (0x31A0, 0x31BF, "Bopomofo Extended"),
- (0xFF00, 0xFFEF, "Halfwidth and Fullwidth Forms"),
- (0x3040, 0x309F, "Hiragana"),
- (0x30A0, 0x30FF, "Katakana"),
- (0x31F0, 0x31FF, "Katakana Phonetic Extensions"),
- (0x1B000, 0x1B0FF, "Kana Supplement"),
- (0xAC00, 0xD7AF, "Hangul Syllables"),
- (0x1100, 0x11FF, "Hangul Jamo"),
- (0xA960, 0xA97F, "Hangul Jamo Extended A"),
- (0xD7B0, 0xD7FF, "Hangul Jamo Extended B"),
- (0x3130, 0x318F, "Hangul Compatibility Jamo"),
- (0xA4D0, 0xA4FF, "Lisu"),
- (0x16F00, 0x16F9F, "Miao"),
- (0xA000, 0xA48F, "Yi Syllables"),
- (0xA490, 0xA4CF, "Yi Radicals"),
-]
-
-_cjk_min_max = None
-
-
-def is_CJK(c) -> bool:
- global _cjk_min_max
- if not _cjk_min_max:
- # cache some values for fast path
- _cjk_min_max = (
- min(x[0] for x in CJK_INTERVALS),
- max(x[1] for x in CJK_INTERVALS),
- )
- n = ord(c)
- if n < _cjk_min_max[0] or n > _cjk_min_max[1]:
- # Fast path -- n is clearly out of range.
- return False
- # Slow path: n may be in range of one of the intervals so scan them all using a slow linear search
- for imin, imax, name in CJK_INTERVALS:
- if n >= imin and n <= imax:
- return True
- return False
-
-
-def normalize_text(seed: str, is_passphrase=False) -> str:
- # normalize
- seed = unicodedata.normalize("NFKD", seed)
- # lower
- if not is_passphrase:
- seed = seed.lower()
- # normalize whitespaces
- seed = " ".join(seed.split())
- # remove whitespaces between CJK
- seed = "".join(
- [
- seed[i]
- for i in range(len(seed))
- if not (
- seed[i] in string.whitespace
- and is_CJK(seed[i - 1])
- and is_CJK(seed[i + 1])
- )
- ]
- )
- return seed
-
-
-def load_wordlist(filename: str) -> List[str]:
- data = pkgutil.get_data(__name__, os.path.join("wordlist", filename))
- s = data.decode("utf-8").strip()
- s = unicodedata.normalize("NFKD", s)
- lines = s.split("\n")
- wordlist = []
- for line in lines:
- line = line.split("#")[0]
- line = line.strip(" \r")
- assert " " not in line
- if line:
- wordlist.append(normalize_text(line))
- return wordlist
-
+from .wordlist import Wordlist, normalize_text
filenames = {
"en": "english.txt",
"es": "spanish.txt",
"ja": "japanese.txt",
"pt": "portuguese.txt",
"zh": "chinese_simplified.txt",
}
@unique
class SeedType(IntEnum):
BIP39 = auto()
Electrum = auto()
Old = auto()
seed_type_names = {
SeedType.BIP39: "bip39",
SeedType.Electrum: "electrum",
SeedType.Old: "old",
}
seed_type_names_inv = {
"bip39": SeedType.BIP39,
"electrum": SeedType.Electrum,
"standard": SeedType.Electrum, # this was the old name for this type
"old": SeedType.Old,
}
def autodetect_seed_type(
seed: str, lang: Optional[str] = None, *, prefix: str = version.SEED_PREFIX
) -> Set[SeedType]:
"""Given a mnemonic seed phrase, auto-detect the possible seed types it can
be. Note that some lucky seed phrases match all three types. Electron Cash
will never generate a seed that matches more than one type, but it is
possible for imported seeds to be ambiguous. May return the empty set if the
seed phrase is invalid and/or fails checksum checks for all three types."""
ret = set()
if is_bip39_seed(seed):
ret.add(SeedType.BIP39)
if is_electrum_seed(seed, prefix):
ret.add(SeedType.Electrum)
if is_old_seed(seed):
ret.add(SeedType.Old)
return ret
def is_bip39_seed(seed: str) -> bool:
"""Checks if `seed` is a valid BIP39 seed phrase (passes wordlist AND
checksum tests)."""
try:
language = mnemonic.Mnemonic.detect_language(seed)
except Exception:
return False
mnemo = mnemonic.Mnemonic(language)
return mnemo.check(seed)
def is_electrum_seed(seed: str, prefix: str = version.SEED_PREFIX) -> bool:
"""Checks if `seed` is a valid Electrum seed phrase.
Returns True if the text in question matches the checksum for Electrum
seeds. Does not depend on any particular word list, just checks unicode
data. Very fast."""
return MnemonicElectrum.verify_checksum_only(seed, prefix)
def is_old_seed(seed: str) -> bool:
"""Returns True if `seed` is a valid "old" seed phrase of 12 or 24 words
*OR* if it's a hex string encoding 16 or 32 bytes."""
seed = normalize_text(seed)
words = seed.split()
try:
# checks here are deliberately left weak for legacy reasons, see #3149
old_mnemonic.mn_decode(words)
uses_electrum_words = True
except Exception:
uses_electrum_words = False
try:
seed = bytes.fromhex(seed)
is_hex = len(seed) == 16 or len(seed) == 32
except Exception:
is_hex = False
return is_hex or (uses_electrum_words and (len(words) == 12 or len(words) == 24))
def seed_type(seed: str) -> Optional[SeedType]:
if is_old_seed(seed):
return SeedType.Old
elif is_electrum_seed(seed):
return SeedType.Electrum
elif is_bip39_seed(seed):
return SeedType.BIP39
def seed_type_name(seed: str) -> str:
return seed_type_names.get(seed_type(seed), "")
def format_seed_type_name_for_ui(name: str) -> str:
"""Given a seed type name e.g. bip39 or standard, transforms it to a
canonical UI string "BIP39" or "Electrum" """
name = name.strip().lower() # paranoia
name = (
seed_type_names.get(seed_type_names_inv.get(name)) or name
) # transforms 'standard' -> 'electrum'
if name == "bip39":
return name.upper()
else:
return name.title() # Title Caps for "Old" and "Electrum"
def is_seed(text: str) -> bool:
return seed_type(text) is not None
def bip39_mnemonic_to_seed(words: str, passphrase: str = ""):
language = mnemonic.Mnemonic.detect_language(words)
return mnemonic.Mnemonic(language).to_seed(words, passphrase)
def make_bip39_words(language) -> str:
"""Return a new 12 words BIP39 seed phrase."""
return mnemonic.Mnemonic(language).generate(strength=128)
class MnemonicBase(PrintError):
"""Base class for both Mnemonic (BIP39-based) and Mnemonic_Electrum.
They both use the same word list, so the commonality between them is
captured in this class."""
- class Data:
- """Each instance of Mnemonic* shares common Data, per language."""
-
- words: Tuple[str] = None
- word_indices: Dict[str, int] = None
-
- shared_datas = weakref.WeakValueDictionary() # key: 2-char lang -> weakvalue: Data
-
def __init__(self, lang=None):
if isinstance(lang, str):
lang = lang[:2].lower()
if lang not in filenames:
lang = "en"
self.lang = lang
- self.data = self.shared_datas.get(lang)
- if not self.data:
- self.data = self.Data()
- self.print_error("loading wordlist for:", lang)
- filename = filenames[lang]
- self.data.words = tuple(load_wordlist(filename))
- self.data.word_indices = {}
- for i, word in enumerate(self.data.words):
- # saves on O(N) lookups for words. The alternative is to call
- # wordlist.index(w) for each word which is slow.
- self.data.word_indices[word] = i
- self.print_error("wordlist has %d words" % len(self.data.words))
- # Paranoia to ensure word list is composed of unique words.
- assert len(self.data.words) == len(self.data.word_indices)
- self.shared_datas[self.lang] = self.data
-
- @property
- def wordlist(self) -> Tuple[str]:
- return self.data.words
-
- @property
- def wordlist_indices(self) -> Dict[str, int]:
- return self.data.word_indices
+ self.print_error("loading wordlist for:", lang)
+ filename = filenames[lang]
+ self.wordlist = Wordlist.from_file(filename)
def get_suggestions(self, prefix):
for w in self.wordlist:
if w.startswith(prefix):
yield w
@classmethod
def list_languages(cls) -> List[str]:
return list(filenames.keys())
@classmethod
def normalize_text(cls, txt: Union[str, bytes], is_passphrase=False) -> str:
if isinstance(txt, bytes):
txt = txt.decode("utf8")
elif not isinstance(txt, str): # noqa: F821
raise TypeError("String value expected")
return normalize_text(txt, is_passphrase=is_passphrase)
@classmethod
def detect_language(cls, code: str) -> str:
code = cls.normalize_text(code)
first = code.split(" ")[0]
languages = cls.list_languages()
for lang in languages:
mnemo = cls(lang)
if first in mnemo.wordlist:
return lang
raise Exception("Language not detected")
@classmethod
def mnemonic_to_seed(cls, mnemonic: str, passphrase: Optional[str]) -> bytes:
raise NotImplementedError(
f"mnemonic_to_seed is not implemented in {cls.__name__}"
)
def make_seed(self, seed_type=None, num_bits=128, custom_entropy=1) -> str:
raise NotImplementedError(
f"make_seed is not implemented in {type(self).__name__}"
)
@classmethod
def is_wordlist_valid(
cls, mnemonic: str, lang: Optional[str] = None
) -> Tuple[bool, str]:
"""Returns (True, lang) if the passed-in `mnemonic` phrase has all its
words found in the wordlist for `lang`. Pass in a None value for `lang`
to auto-detect language. The fallback language is always "en".
If the `mnemonic` contains any word not in the wordlist for `lang`,
returns (False, lang) if lang was specified or (False, "en") if it was
not."""
if lang is None:
try:
lang = cls.detect_language(mnemonic)
except Exception:
lang = "en"
elif lang not in cls.list_languages():
lang = "en"
return cls(lang).verify_wordlist(mnemonic), lang
def verify_wordlist(self, mnemonic: str) -> bool:
"""Instance method which is a variation on is_wordlist_valid, which
does no language detection and simply checks all of the words in
mnemonic versus this instance's wordlist, returns True if they are all
in the wordlist."""
mnemonic = self.normalize_text(mnemonic)
for w in mnemonic.split():
- if w not in self.wordlist_indices:
+ if w not in self.wordlist:
return False
return True
def is_checksum_valid(self, mnemonic: str) -> Tuple[bool, bool]:
raise NotImplementedError(
f"is_checksum_valid is not implemented in {type(self).__name__}"
)
def is_seed(self, mnemonic: str) -> bool:
"""Convenient alias for is_checksum_valid()[0]"""
return self.is_checksum_valid(mnemonic)[0]
class MnemonicElectrum(MnemonicBase):
"""This implements the "Electrum" mnemonic seed phrase format, which was
used for many years, but starting in 2020, Electron Cash switched back to
BIP39 since it has wider support.
The Electrum seed phrase format uses a hash based checksum of the normalized
text data, instead of a wordlist-dependent checksum."""
@classmethod
def mnemonic_to_seed(cls, mnemonic, passphrase):
"""Electrum format"""
PBKDF2_ROUNDS = 2048
mnemonic = cls.normalize_text(mnemonic)
passphrase = cls.normalize_text(passphrase or "", is_passphrase=True)
return hashlib.pbkdf2_hmac(
"sha512",
mnemonic.encode("utf-8"),
b"electrum" + passphrase.encode("utf-8"),
iterations=PBKDF2_ROUNDS,
)
def mnemonic_encode(self, i):
n = len(self.wordlist)
words = []
while i:
x = i % n
i = i // n
words.append(self.wordlist[x])
return " ".join(words)
def mnemonic_decode(self, seed):
n = len(self.wordlist)
i = 0
for w in reversed(seed.split()):
- k = self.wordlist_indices[w]
+ k = self.wordlist.index(w)
i = i * n + k
return i
def make_seed(self, seed_type=None, num_bits=132, custom_entropy=1):
"""Electrum format"""
if self.lang not in ("en", "es", "pt"):
raise NotImplementedError(
f"Cannot make a seed for language '{self.lang}'. "
+ "Only English, Spanish, and Portuguese are supported as seed"
" generation languages in this implementation"
)
if seed_type is None:
seed_type = "electrum"
prefix = version.seed_prefix(seed_type)
# increase num_bits in order to obtain a uniform distibution for the last word
bpw = math.log(len(self.wordlist), 2)
num_bits = int(math.ceil(num_bits / bpw) * bpw)
# handle custom entropy; make sure we add at least 16 bits
n_custom = int(math.ceil(math.log(custom_entropy, 2)))
n = max(16, num_bits - n_custom)
self.print_error("make_seed", prefix, "adding %d bits" % n)
my_entropy = 1
while my_entropy < pow(2, n - bpw):
# try again if seed would not contain enough words
my_entropy = randrange(pow(2, n))
nonce = 0
while True:
nonce += 1
i = custom_entropy * (my_entropy + nonce)
seed = self.mnemonic_encode(i)
if i != self.mnemonic_decode(seed):
raise Exception("Cannot extract same entropy from mnemonic!")
# avoid ambiguity between old-style seeds and new-style, as well as avoid clashes with BIP39 seeds
if autodetect_seed_type(seed, self.lang, prefix=prefix) == {
SeedType.Electrum
}:
break
self.print_error(
"{nwords} words, {nonce} iterations".format(
nwords=len(seed.split()), nonce=nonce
)
)
return seed
def check_seed(self, seed: str, custom_entropy: int) -> bool:
assert self.verify_checksum_only(seed)
i = self.mnemonic_decode(seed)
return i % custom_entropy == 0
def is_checksum_valid(
self, mnemonic: str, *, prefix: str = version.SEED_PREFIX
) -> Tuple[bool, bool]:
return self.verify_checksum_only(mnemonic, prefix), self.verify_wordlist(
mnemonic
)
@classmethod
def verify_checksum_only(
cls, mnemonic: str, prefix: str = version.SEED_PREFIX
) -> bool:
x = cls.normalize_text(mnemonic)
s = hmac_sha_512(b"Seed version", x.encode("utf8")).hex()
return s.startswith(prefix)
def is_seed(self, mnemonic: str) -> bool:
"""Overrides super, skips the wordlist check which is not needed to
answer this question for Electrum seeds."""
return self.verify_checksum_only(mnemonic)
diff --git a/electrum/electrumabc/old_mnemonic.py b/electrum/electrumabc/old_mnemonic.py
index 8218a728c..23d150d63 100644
--- a/electrum/electrumabc/old_mnemonic.py
+++ b/electrum/electrumabc/old_mnemonic.py
@@ -1,1697 +1,1701 @@
#
# Electrum ABC - lightweight eCash client
# Copyright (C) 2020 The Electrum ABC developers
# Copyright (C) 2011 thomasv@gitorious
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
+from .wordlist import Wordlist
+
# list of words from http://en.wiktionary.org/wiki/Wiktionary:Frequency_lists/Contemporary_poetry
-words = [
+_words = [
"like",
"just",
"love",
"know",
"never",
"want",
"time",
"out",
"there",
"make",
"look",
"eye",
"down",
"only",
"think",
"heart",
"back",
"then",
"into",
"about",
"more",
"away",
"still",
"them",
"take",
"thing",
"even",
"through",
"long",
"always",
"world",
"too",
"friend",
"tell",
"try",
"hand",
"thought",
"over",
"here",
"other",
"need",
"smile",
"again",
"much",
"cry",
"been",
"night",
"ever",
"little",
"said",
"end",
"some",
"those",
"around",
"mind",
"people",
"girl",
"leave",
"dream",
"left",
"turn",
"myself",
"give",
"nothing",
"really",
"off",
"before",
"something",
"find",
"walk",
"wish",
"good",
"once",
"place",
"ask",
"stop",
"keep",
"watch",
"seem",
"everything",
"wait",
"got",
"yet",
"made",
"remember",
"start",
"alone",
"run",
"hope",
"maybe",
"believe",
"body",
"hate",
"after",
"close",
"talk",
"stand",
"own",
"each",
"hurt",
"help",
"home",
"god",
"soul",
"new",
"many",
"two",
"inside",
"should",
"true",
"first",
"fear",
"mean",
"better",
"play",
"another",
"gone",
"change",
"use",
"wonder",
"someone",
"hair",
"cold",
"open",
"best",
"any",
"behind",
"happen",
"water",
"dark",
"laugh",
"stay",
"forever",
"name",
"work",
"show",
"sky",
"break",
"came",
"deep",
"door",
"put",
"black",
"together",
"upon",
"happy",
"such",
"great",
"white",
"matter",
"fill",
"past",
"please",
"burn",
"cause",
"enough",
"touch",
"moment",
"soon",
"voice",
"scream",
"anything",
"stare",
"sound",
"red",
"everyone",
"hide",
"kiss",
"truth",
"death",
"beautiful",
"mine",
"blood",
"broken",
"very",
"pass",
"next",
"forget",
"tree",
"wrong",
"air",
"mother",
"understand",
"lip",
"hit",
"wall",
"memory",
"sleep",
"free",
"high",
"realize",
"school",
"might",
"skin",
"sweet",
"perfect",
"blue",
"kill",
"breath",
"dance",
"against",
"fly",
"between",
"grow",
"strong",
"under",
"listen",
"bring",
"sometimes",
"speak",
"pull",
"person",
"become",
"family",
"begin",
"ground",
"real",
"small",
"father",
"sure",
"feet",
"rest",
"young",
"finally",
"land",
"across",
"today",
"different",
"guy",
"line",
"fire",
"reason",
"reach",
"second",
"slowly",
"write",
"eat",
"smell",
"mouth",
"step",
"learn",
"three",
"floor",
"promise",
"breathe",
"darkness",
"push",
"earth",
"guess",
"save",
"song",
"above",
"along",
"both",
"color",
"house",
"almost",
"sorry",
"anymore",
"brother",
"okay",
"dear",
"game",
"fade",
"already",
"apart",
"warm",
"beauty",
"heard",
"notice",
"question",
"shine",
"began",
"piece",
"whole",
"shadow",
"secret",
"street",
"within",
"finger",
"point",
"morning",
"whisper",
"child",
"moon",
"green",
"story",
"glass",
"kid",
"silence",
"since",
"soft",
"yourself",
"empty",
"shall",
"angel",
"answer",
"baby",
"bright",
"dad",
"path",
"worry",
"hour",
"drop",
"follow",
"power",
"war",
"half",
"flow",
"heaven",
"act",
"chance",
"fact",
"least",
"tired",
"children",
"near",
"quite",
"afraid",
"rise",
"sea",
"taste",
"window",
"cover",
"nice",
"trust",
"lot",
"sad",
"cool",
"force",
"peace",
"return",
"blind",
"easy",
"ready",
"roll",
"rose",
"drive",
"held",
"music",
"beneath",
"hang",
"mom",
"paint",
"emotion",
"quiet",
"clear",
"cloud",
"few",
"pretty",
"bird",
"outside",
"paper",
"picture",
"front",
"rock",
"simple",
"anyone",
"meant",
"reality",
"road",
"sense",
"waste",
"bit",
"leaf",
"thank",
"happiness",
"meet",
"men",
"smoke",
"truly",
"decide",
"self",
"age",
"book",
"form",
"alive",
"carry",
"escape",
"damn",
"instead",
"able",
"ice",
"minute",
"throw",
"catch",
"leg",
"ring",
"course",
"goodbye",
"lead",
"poem",
"sick",
"corner",
"desire",
"known",
"problem",
"remind",
"shoulder",
"suppose",
"toward",
"wave",
"drink",
"jump",
"woman",
"pretend",
"sister",
"week",
"human",
"joy",
"crack",
"grey",
"pray",
"surprise",
"dry",
"knee",
"less",
"search",
"bleed",
"caught",
"clean",
"embrace",
"future",
"king",
"son",
"sorrow",
"chest",
"hug",
"remain",
"sat",
"worth",
"blow",
"daddy",
"final",
"parent",
"tight",
"also",
"create",
"lonely",
"safe",
"cross",
"dress",
"evil",
"silent",
"bone",
"fate",
"perhaps",
"anger",
"class",
"scar",
"snow",
"tiny",
"tonight",
"continue",
"control",
"dog",
"edge",
"mirror",
"month",
"suddenly",
"comfort",
"given",
"loud",
"quickly",
"gaze",
"plan",
"rush",
"stone",
"town",
"battle",
"ignore",
"spirit",
"stood",
"stupid",
"yours",
"brown",
"build",
"dust",
"hey",
"kept",
"pay",
"phone",
"twist",
"although",
"ball",
"beyond",
"hidden",
"nose",
"taken",
"fail",
"float",
"pure",
"somehow",
"wash",
"wrap",
"angry",
"cheek",
"creature",
"forgotten",
"heat",
"rip",
"single",
"space",
"special",
"weak",
"whatever",
"yell",
"anyway",
"blame",
"job",
"choose",
"country",
"curse",
"drift",
"echo",
"figure",
"grew",
"laughter",
"neck",
"suffer",
"worse",
"yeah",
"disappear",
"foot",
"forward",
"knife",
"mess",
"somewhere",
"stomach",
"storm",
"beg",
"idea",
"lift",
"offer",
"breeze",
"field",
"five",
"often",
"simply",
"stuck",
"win",
"allow",
"confuse",
"enjoy",
"except",
"flower",
"seek",
"strength",
"calm",
"grin",
"gun",
"heavy",
"hill",
"large",
"ocean",
"shoe",
"sigh",
"straight",
"summer",
"tongue",
"accept",
"crazy",
"everyday",
"exist",
"grass",
"mistake",
"sent",
"shut",
"surround",
"table",
"ache",
"brain",
"destroy",
"heal",
"nature",
"shout",
"sign",
"stain",
"choice",
"doubt",
"glance",
"glow",
"mountain",
"queen",
"stranger",
"throat",
"tomorrow",
"city",
"either",
"fish",
"flame",
"rather",
"shape",
"spin",
"spread",
"ash",
"distance",
"finish",
"image",
"imagine",
"important",
"nobody",
"shatter",
"warmth",
"became",
"feed",
"flesh",
"funny",
"lust",
"shirt",
"trouble",
"yellow",
"attention",
"bare",
"bite",
"money",
"protect",
"amaze",
"appear",
"born",
"choke",
"completely",
"daughter",
"fresh",
"friendship",
"gentle",
"probably",
"six",
"deserve",
"expect",
"grab",
"middle",
"nightmare",
"river",
"thousand",
"weight",
"worst",
"wound",
"barely",
"bottle",
"cream",
"regret",
"relationship",
"stick",
"test",
"crush",
"endless",
"fault",
"itself",
"rule",
"spill",
"art",
"circle",
"join",
"kick",
"mask",
"master",
"passion",
"quick",
"raise",
"smooth",
"unless",
"wander",
"actually",
"broke",
"chair",
"deal",
"favorite",
"gift",
"note",
"number",
"sweat",
"box",
"chill",
"clothes",
"lady",
"mark",
"park",
"poor",
"sadness",
"tie",
"animal",
"belong",
"brush",
"consume",
"dawn",
"forest",
"innocent",
"pen",
"pride",
"stream",
"thick",
"clay",
"complete",
"count",
"draw",
"faith",
"press",
"silver",
"struggle",
"surface",
"taught",
"teach",
"wet",
"bless",
"chase",
"climb",
"enter",
"letter",
"melt",
"metal",
"movie",
"stretch",
"swing",
"vision",
"wife",
"beside",
"crash",
"forgot",
"guide",
"haunt",
"joke",
"knock",
"plant",
"pour",
"prove",
"reveal",
"steal",
"stuff",
"trip",
"wood",
"wrist",
"bother",
"bottom",
"crawl",
"crowd",
"fix",
"forgive",
"frown",
"grace",
"loose",
"lucky",
"party",
"release",
"surely",
"survive",
"teacher",
"gently",
"grip",
"speed",
"suicide",
"travel",
"treat",
"vein",
"written",
"cage",
"chain",
"conversation",
"date",
"enemy",
"however",
"interest",
"million",
"page",
"pink",
"proud",
"sway",
"themselves",
"winter",
"church",
"cruel",
"cup",
"demon",
"experience",
"freedom",
"pair",
"pop",
"purpose",
"respect",
"shoot",
"softly",
"state",
"strange",
"bar",
"birth",
"curl",
"dirt",
"excuse",
"lord",
"lovely",
"monster",
"order",
"pack",
"pants",
"pool",
"scene",
"seven",
"shame",
"slide",
"ugly",
"among",
"blade",
"blonde",
"closet",
"creek",
"deny",
"drug",
"eternity",
"gain",
"grade",
"handle",
"key",
"linger",
"pale",
"prepare",
"swallow",
"swim",
"tremble",
"wheel",
"won",
"cast",
"cigarette",
"claim",
"college",
"direction",
"dirty",
"gather",
"ghost",
"hundred",
"loss",
"lung",
"orange",
"present",
"swear",
"swirl",
"twice",
"wild",
"bitter",
"blanket",
"doctor",
"everywhere",
"flash",
"grown",
"knowledge",
"numb",
"pressure",
"radio",
"repeat",
"ruin",
"spend",
"unknown",
"buy",
"clock",
"devil",
"early",
"false",
"fantasy",
"pound",
"precious",
"refuse",
"sheet",
"teeth",
"welcome",
"add",
"ahead",
"block",
"bury",
"caress",
"content",
"depth",
"despite",
"distant",
"marry",
"purple",
"threw",
"whenever",
"bomb",
"dull",
"easily",
"grasp",
"hospital",
"innocence",
"normal",
"receive",
"reply",
"rhyme",
"shade",
"someday",
"sword",
"toe",
"visit",
"asleep",
"bought",
"center",
"consider",
"flat",
"hero",
"history",
"ink",
"insane",
"muscle",
"mystery",
"pocket",
"reflection",
"shove",
"silently",
"smart",
"soldier",
"spot",
"stress",
"train",
"type",
"view",
"whether",
"bus",
"energy",
"explain",
"holy",
"hunger",
"inch",
"magic",
"mix",
"noise",
"nowhere",
"prayer",
"presence",
"shock",
"snap",
"spider",
"study",
"thunder",
"trail",
"admit",
"agree",
"bag",
"bang",
"bound",
"butterfly",
"cute",
"exactly",
"explode",
"familiar",
"fold",
"further",
"pierce",
"reflect",
"scent",
"selfish",
"sharp",
"sink",
"spring",
"stumble",
"universe",
"weep",
"women",
"wonderful",
"action",
"ancient",
"attempt",
"avoid",
"birthday",
"branch",
"chocolate",
"core",
"depress",
"drunk",
"especially",
"focus",
"fruit",
"honest",
"match",
"palm",
"perfectly",
"pillow",
"pity",
"poison",
"roar",
"shift",
"slightly",
"thump",
"truck",
"tune",
"twenty",
"unable",
"wipe",
"wrote",
"coat",
"constant",
"dinner",
"drove",
"egg",
"eternal",
"flight",
"flood",
"frame",
"freak",
"gasp",
"glad",
"hollow",
"motion",
"peer",
"plastic",
"root",
"screen",
"season",
"sting",
"strike",
"team",
"unlike",
"victim",
"volume",
"warn",
"weird",
"attack",
"await",
"awake",
"built",
"charm",
"crave",
"despair",
"fought",
"grant",
"grief",
"horse",
"limit",
"message",
"ripple",
"sanity",
"scatter",
"serve",
"split",
"string",
"trick",
"annoy",
"blur",
"boat",
"brave",
"clearly",
"cling",
"connect",
"fist",
"forth",
"imagination",
"iron",
"jock",
"judge",
"lesson",
"milk",
"misery",
"nail",
"naked",
"ourselves",
"poet",
"possible",
"princess",
"sail",
"size",
"snake",
"society",
"stroke",
"torture",
"toss",
"trace",
"wise",
"bloom",
"bullet",
"cell",
"check",
"cost",
"darling",
"during",
"footstep",
"fragile",
"hallway",
"hardly",
"horizon",
"invisible",
"journey",
"midnight",
"mud",
"nod",
"pause",
"relax",
"shiver",
"sudden",
"value",
"youth",
"abuse",
"admire",
"blink",
"breast",
"bruise",
"constantly",
"couple",
"creep",
"curve",
"difference",
"dumb",
"emptiness",
"gotta",
"honor",
"plain",
"planet",
"recall",
"rub",
"ship",
"slam",
"soar",
"somebody",
"tightly",
"weather",
"adore",
"approach",
"bond",
"bread",
"burst",
"candle",
"coffee",
"cousin",
"crime",
"desert",
"flutter",
"frozen",
"grand",
"heel",
"hello",
"language",
"level",
"movement",
"pleasure",
"powerful",
"random",
"rhythm",
"settle",
"silly",
"slap",
"sort",
"spoken",
"steel",
"threaten",
"tumble",
"upset",
"aside",
"awkward",
"bee",
"blank",
"board",
"button",
"card",
"carefully",
"complain",
"crap",
"deeply",
"discover",
"drag",
"dread",
"effort",
"entire",
"fairy",
"giant",
"gotten",
"greet",
"illusion",
"jeans",
"leap",
"liquid",
"march",
"mend",
"nervous",
"nine",
"replace",
"rope",
"spine",
"stole",
"terror",
"accident",
"apple",
"balance",
"boom",
"childhood",
"collect",
"demand",
"depression",
"eventually",
"faint",
"glare",
"goal",
"group",
"honey",
"kitchen",
"laid",
"limb",
"machine",
"mere",
"mold",
"murder",
"nerve",
"painful",
"poetry",
"prince",
"rabbit",
"shelter",
"shore",
"shower",
"soothe",
"stair",
"steady",
"sunlight",
"tangle",
"tease",
"treasure",
"uncle",
"begun",
"bliss",
"canvas",
"cheer",
"claw",
"clutch",
"commit",
"crimson",
"crystal",
"delight",
"doll",
"existence",
"express",
"fog",
"football",
"gay",
"goose",
"guard",
"hatred",
"illuminate",
"mass",
"math",
"mourn",
"rich",
"rough",
"skip",
"stir",
"student",
"style",
"support",
"thorn",
"tough",
"yard",
"yearn",
"yesterday",
"advice",
"appreciate",
"autumn",
"bank",
"beam",
"bowl",
"capture",
"carve",
"collapse",
"confusion",
"creation",
"dove",
"feather",
"girlfriend",
"glory",
"government",
"harsh",
"hop",
"inner",
"loser",
"moonlight",
"neighbor",
"neither",
"peach",
"pig",
"praise",
"screw",
"shield",
"shimmer",
"sneak",
"stab",
"subject",
"throughout",
"thrown",
"tower",
"twirl",
"wow",
"army",
"arrive",
"bathroom",
"bump",
"cease",
"cookie",
"couch",
"courage",
"dim",
"guilt",
"howl",
"hum",
"husband",
"insult",
"led",
"lunch",
"mock",
"mostly",
"natural",
"nearly",
"needle",
"nerd",
"peaceful",
"perfection",
"pile",
"price",
"remove",
"roam",
"sanctuary",
"serious",
"shiny",
"shook",
"sob",
"stolen",
"tap",
"vain",
"void",
"warrior",
"wrinkle",
"affection",
"apologize",
"blossom",
"bounce",
"bridge",
"cheap",
"crumble",
"decision",
"descend",
"desperately",
"dig",
"dot",
"flip",
"frighten",
"heartbeat",
"huge",
"lazy",
"lick",
"odd",
"opinion",
"process",
"puzzle",
"quietly",
"retreat",
"score",
"sentence",
"separate",
"situation",
"skill",
"soak",
"square",
"stray",
"taint",
"task",
"tide",
"underneath",
"veil",
"whistle",
"anywhere",
"bedroom",
"bid",
"bloody",
"burden",
"careful",
"compare",
"concern",
"curtain",
"decay",
"defeat",
"describe",
"double",
"dreamer",
"driver",
"dwell",
"evening",
"flare",
"flicker",
"grandma",
"guitar",
"harm",
"horrible",
"hungry",
"indeed",
"lace",
"melody",
"monkey",
"nation",
"object",
"obviously",
"rainbow",
"salt",
"scratch",
"shown",
"shy",
"stage",
"stun",
"third",
"tickle",
"useless",
"weakness",
"worship",
"worthless",
"afternoon",
"beard",
"boyfriend",
"bubble",
"busy",
"certain",
"chin",
"concrete",
"desk",
"diamond",
"doom",
"drawn",
"due",
"felicity",
"freeze",
"frost",
"garden",
"glide",
"harmony",
"hopefully",
"hunt",
"jealous",
"lightning",
"mama",
"mercy",
"peel",
"physical",
"position",
"pulse",
"punch",
"quit",
"rant",
"respond",
"salty",
"sane",
"satisfy",
"savior",
"sheep",
"slept",
"social",
"sport",
"tuck",
"utter",
"valley",
"wolf",
"aim",
"alas",
"alter",
"arrow",
"awaken",
"beaten",
"belief",
"brand",
"ceiling",
"cheese",
"clue",
"confidence",
"connection",
"daily",
"disguise",
"eager",
"erase",
"essence",
"everytime",
"expression",
"fan",
"flag",
"flirt",
"foul",
"fur",
"giggle",
"glorious",
"ignorance",
"law",
"lifeless",
"measure",
"mighty",
"muse",
"north",
"opposite",
"paradise",
"patience",
"patient",
"pencil",
"petal",
"plate",
"ponder",
"possibly",
"practice",
"slice",
"spell",
"stock",
"strife",
"strip",
"suffocate",
"suit",
"tender",
"tool",
"trade",
"velvet",
"verse",
"waist",
"witch",
"aunt",
"bench",
"bold",
"cap",
"certainly",
"click",
"companion",
"creator",
"dart",
"delicate",
"determine",
"dish",
"dragon",
"drama",
"drum",
"dude",
"everybody",
"feast",
"forehead",
"former",
"fright",
"fully",
"gas",
"hook",
"hurl",
"invite",
"juice",
"manage",
"moral",
"possess",
"raw",
"rebel",
"royal",
"scale",
"scary",
"several",
"slight",
"stubborn",
"swell",
"talent",
"tea",
"terrible",
"thread",
"torment",
"trickle",
"usually",
"vast",
"violence",
"weave",
"acid",
"agony",
"ashamed",
"awe",
"belly",
"blend",
"blush",
"character",
"cheat",
"common",
"company",
"coward",
"creak",
"danger",
"deadly",
"defense",
"define",
"depend",
"desperate",
"destination",
"dew",
"duck",
"dusty",
"embarrass",
"engine",
"example",
"explore",
"foe",
"freely",
"frustrate",
"generation",
"glove",
"guilty",
"health",
"hurry",
"idiot",
"impossible",
"inhale",
"jaw",
"kingdom",
"mention",
"mist",
"moan",
"mumble",
"mutter",
"observe",
"ode",
"pathetic",
"pattern",
"pie",
"prefer",
"puff",
"rape",
"rare",
"revenge",
"rude",
"scrape",
"spiral",
"squeeze",
"strain",
"sunset",
"suspend",
"sympathy",
"thigh",
"throne",
"total",
"unseen",
"weapon",
"weary",
]
+wordlist = Wordlist(_words)
-n = 1626
+n = len(wordlist)
+assert n == 1626
# Note about US patent no 5892470: Here each word does not represent a given digit.
# Instead, the digit represented by a word is variable, it depends on the previous word.
def mn_encode(message):
assert len(message) % 8 == 0
out = []
for i in range(len(message) // 8):
word = message[8 * i : 8 * i + 8]
x = int(word, 16)
w1 = x % n
w2 = ((x // n) + w1) % n
w3 = ((x // n // n) + w2) % n
- out += [words[w1], words[w2], words[w3]]
+ out += [wordlist[w1], wordlist[w2], wordlist[w3]]
return out
def mn_decode(wlist):
out = ""
for i in range(len(wlist) // 3):
word1, word2, word3 = wlist[3 * i : 3 * i + 3]
- w1 = words.index(word1)
- w2 = (words.index(word2)) % n
- w3 = (words.index(word3)) % n
+ w1 = wordlist.index(word1)
+ w2 = (wordlist.index(word2)) % n
+ w3 = (wordlist.index(word3)) % n
x = w1 + n * ((w2 - w1) % n) + n * n * ((w3 - w2) % n)
out += "%08x" % x
return out
if __name__ == "__main__":
import sys
if len(sys.argv) == 1:
print("I need arguments: a hex string to encode, or a list of words to decode")
elif len(sys.argv) == 2:
print(" ".join(mn_encode(sys.argv[1])))
else:
print(mn_decode(sys.argv[1:]))
diff --git a/electrum/electrumabc/wordlist.py b/electrum/electrumabc/wordlist.py
new file mode 100644
index 000000000..b4ab1bd73
--- /dev/null
+++ b/electrum/electrumabc/wordlist.py
@@ -0,0 +1,148 @@
+# Electrum - lightweight Bitcoin client
+# Copyright (C) 2018 Thomas Voegtlin
+#
+# Permission is hereby granted, free of charge, to any person
+# obtaining a copy of this software and associated documentation files
+# (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, sublicense, and/or sell copies of the Software,
+# and to permit persons to whom the Software is furnished to do so,
+# subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be
+# included in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+# CONNECTION WIT
+
+import os
+import pkgutil
+import string
+import unicodedata
+from types import MappingProxyType
+from typing import Sequence
+
+# http://www.asahi-net.or.jp/~ax2s-kmtn/ref/unicode/e_asia.html
+CJK_INTERVALS = [
+ (0x4E00, 0x9FFF, "CJK Unified Ideographs"),
+ (0x3400, 0x4DBF, "CJK Unified Ideographs Extension A"),
+ (0x20000, 0x2A6DF, "CJK Unified Ideographs Extension B"),
+ (0x2A700, 0x2B73F, "CJK Unified Ideographs Extension C"),
+ (0x2B740, 0x2B81F, "CJK Unified Ideographs Extension D"),
+ (0xF900, 0xFAFF, "CJK Compatibility Ideographs"),
+ (0x2F800, 0x2FA1D, "CJK Compatibility Ideographs Supplement"),
+ (0x3190, 0x319F, "Kanbun"),
+ (0x2E80, 0x2EFF, "CJK Radicals Supplement"),
+ (0x2F00, 0x2FDF, "CJK Radicals"),
+ (0x31C0, 0x31EF, "CJK Strokes"),
+ (0x2FF0, 0x2FFF, "Ideographic Description Characters"),
+ (0xE0100, 0xE01EF, "Variation Selectors Supplement"),
+ (0x3100, 0x312F, "Bopomofo"),
+ (0x31A0, 0x31BF, "Bopomofo Extended"),
+ (0xFF00, 0xFFEF, "Halfwidth and Fullwidth Forms"),
+ (0x3040, 0x309F, "Hiragana"),
+ (0x30A0, 0x30FF, "Katakana"),
+ (0x31F0, 0x31FF, "Katakana Phonetic Extensions"),
+ (0x1B000, 0x1B0FF, "Kana Supplement"),
+ (0xAC00, 0xD7AF, "Hangul Syllables"),
+ (0x1100, 0x11FF, "Hangul Jamo"),
+ (0xA960, 0xA97F, "Hangul Jamo Extended A"),
+ (0xD7B0, 0xD7FF, "Hangul Jamo Extended B"),
+ (0x3130, 0x318F, "Hangul Compatibility Jamo"),
+ (0xA4D0, 0xA4FF, "Lisu"),
+ (0x16F00, 0x16F9F, "Miao"),
+ (0xA000, 0xA48F, "Yi Syllables"),
+ (0xA490, 0xA4CF, "Yi Radicals"),
+]
+
+_cjk_min_max = None
+
+
+def is_CJK(c) -> bool:
+ global _cjk_min_max
+ if not _cjk_min_max:
+ # cache some values for fast path
+ _cjk_min_max = (
+ min(x[0] for x in CJK_INTERVALS),
+ max(x[1] for x in CJK_INTERVALS),
+ )
+ n = ord(c)
+ if n < _cjk_min_max[0] or n > _cjk_min_max[1]:
+ # Fast path -- n is clearly out of range.
+ return False
+ # Slow path: n may be in range of one of the intervals so scan them all using a slow linear search
+ for imin, imax, name in CJK_INTERVALS:
+ if n >= imin and n <= imax:
+ return True
+ return False
+
+
+def normalize_text(seed: str, is_passphrase=False) -> str:
+ # normalize
+ seed = unicodedata.normalize("NFKD", seed)
+ # lower
+ if not is_passphrase:
+ seed = seed.lower()
+ # normalize whitespaces
+ seed = " ".join(seed.split())
+ # remove whitespaces between CJK
+ seed = "".join(
+ [
+ seed[i]
+ for i in range(len(seed))
+ if not (
+ seed[i] in string.whitespace
+ and is_CJK(seed[i - 1])
+ and is_CJK(seed[i + 1])
+ )
+ ]
+ )
+ return seed
+
+
+_WORDLIST_CACHE: dict[str, "Wordlist"] = {}
+
+
+class Wordlist(tuple):
+
+ def __init__(self, words: Sequence[str]):
+ super().__init__()
+ index_from_word = {w: i for i, w in enumerate(words)}
+ # no mutation
+ self._index_from_word = MappingProxyType(index_from_word)
+
+ def index(self, word, start=None, stop=None) -> int:
+ try:
+ return self._index_from_word[word]
+ except KeyError as e:
+ raise ValueError from e
+
+ def __contains__(self, word) -> bool:
+ try:
+ self.index(word)
+ except ValueError:
+ return False
+ else:
+ return True
+
+ @classmethod
+ def from_file(cls, filename) -> "Wordlist":
+ if filename not in _WORDLIST_CACHE:
+ data = pkgutil.get_data(__name__, os.path.join("wordlist", filename))
+ s = data.decode("utf-8").strip()
+ s = unicodedata.normalize("NFKD", s)
+ lines = s.split("\n")
+ words = []
+ for line in lines:
+ line = line.split("#")[0]
+ line = line.strip(" \r")
+ assert " " not in line
+ if line:
+ words.append(normalize_text(line))
+ _WORDLIST_CACHE[filename] = Wordlist(words)
+ return _WORDLIST_CACHE[filename]
diff --git a/electrum/electrumabc_gui/qt/seed_dialog.py b/electrum/electrumabc_gui/qt/seed_dialog.py
index ec1f38b5b..38bc34182 100644
--- a/electrum/electrumabc_gui/qt/seed_dialog.py
+++ b/electrum/electrumabc_gui/qt/seed_dialog.py
@@ -1,314 +1,314 @@
#
# Electrum ABC - lightweight eCash client
# Copyright (C) 2020 The Electrum ABC developers
# Copyright (C) 2013 ecdsa@github
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import mnemonic
from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon
from electrumabc import mnemo, old_mnemonic
from electrumabc.constants import PROJECT_NAME
from electrumabc.i18n import _
from .completion_text_edit import CompletionTextEdit
from .qrtextedit import ScanQRTextEdit
from .util import (
Buttons,
CloseButton,
ColorScheme,
EnterButton,
OkButton,
WindowModalDialog,
WWLabel,
)
def seed_warning_msg(seed, has_der=False, has_ext=False):
extra = ""
if has_der:
if has_ext:
extra = (
" "
+ _(
"Additionally, save the seed extension and derivation path as well."
)
+ " "
)
else:
extra = " " + _("Additionally, save the derivation path as well.") + " "
elif has_ext:
extra = " " + _("Additionally, save the seed extension as well.") + " "
return "".join(
[
"<p>",
_("Please save these %d words on paper (order is important). "),
extra,
_(
"This seed will allow you to recover your wallet in case "
"of computer failure."
),
"</p>",
"<b>" + _("WARNING") + ":</b>",
"<ul>",
"<li>" + _("Never disclose your seed.") + "</li>",
"<li>" + _("Never type it on a website.") + "</li>",
"<li>" + _("Do not store it electronically.") + "</li>",
"</ul>",
]
) % len(seed.split())
class SeedLayout(QtWidgets.QVBoxLayout):
# options
is_bip39 = False
is_ext = False
def seed_options(self):
dialog = QtWidgets.QDialog()
vbox = QtWidgets.QVBoxLayout(dialog)
if "ext" in self.options:
cb_ext = QtWidgets.QCheckBox(
_("Extend this seed with custom words") + " " + _("(aka 'passphrase')")
)
cb_ext.setChecked(self.is_ext)
vbox.addWidget(cb_ext)
if "bip39" in self.options:
def f(b):
self.is_seed = (lambda x: bool(x)) if b else self.saved_is_seed
self.is_bip39 = b
self.on_edit()
cb_bip39 = QtWidgets.QCheckBox(_("Force BIP39 interpretation of this seed"))
cb_bip39.toggled.connect(f)
cb_bip39.setChecked(self.is_bip39)
vbox.addWidget(cb_bip39)
vbox.addLayout(Buttons(OkButton(dialog)))
if not dialog.exec_():
return None
self.is_ext = cb_ext.isChecked() if "ext" in self.options else False
self.is_bip39 = cb_bip39.isChecked() if "bip39" in self.options else False
def __init__(
self,
seed=None,
title=None,
icon=True,
msg=None,
options=None,
is_seed=None,
passphrase=None,
parent=None,
editable=True,
derivation=None,
seed_type=None,
):
QtWidgets.QVBoxLayout.__init__(self)
self.parent = parent
self.options = options or ()
if title:
self.addWidget(WWLabel(title))
self.seed_e = CompletionTextEdit()
self.editable = bool(editable)
self.seed_e.setReadOnly(not self.editable)
if seed:
self.seed_e.setText(seed)
else:
self.seed_e.setTabChangesFocus(True)
self.is_seed = is_seed
self.saved_is_seed = self.is_seed
self.seed_e.textChanged.connect(self.on_edit)
self.initialize_completer()
self.seed_e.setMaximumHeight(75)
hbox = QtWidgets.QHBoxLayout()
if icon:
logo = QtWidgets.QLabel()
logo.setPixmap(QIcon(":icons/seed.png").pixmap(64))
logo.setMaximumWidth(60)
hbox.addWidget(logo)
hbox.addWidget(self.seed_e)
self.addLayout(hbox)
hbox = QtWidgets.QHBoxLayout()
hbox.addStretch(1)
self.seed_type_label = QtWidgets.QLabel("")
hbox.addWidget(self.seed_type_label)
if self.options:
opt_button = EnterButton(_("Options"), self.seed_options)
hbox.addWidget(opt_button)
self.addLayout(hbox)
# may not be used if none of the below if expressions evaluates to true,
# that's ok.
grid_maybe = QtWidgets.QGridLayout()
# we want the right-hand column to take up as much space as it needs.
grid_maybe.setColumnStretch(1, 1)
grid_row = 0
if seed_type:
seed_type_text = mnemo.format_seed_type_name_for_ui(seed_type)
grid_maybe.addWidget(QtWidgets.QLabel(_("Seed format") + ":"), grid_row, 0)
grid_maybe.addWidget(
QtWidgets.QLabel(f"<b>{seed_type_text}</b>"), grid_row, 1, Qt.AlignLeft
)
grid_row += 1
if passphrase:
passphrase_e = QtWidgets.QLineEdit()
passphrase_e.setText(passphrase)
passphrase_e.setReadOnly(True)
grid_maybe.addWidget(
QtWidgets.QLabel(_("Your seed extension is") + ":"), grid_row, 0
)
grid_maybe.addWidget(passphrase_e, grid_row, 1)
grid_row += 1
if derivation:
der_e = QtWidgets.QLineEdit()
der_e.setText(str(derivation))
der_e.setReadOnly(True)
grid_maybe.addWidget(
QtWidgets.QLabel(_("Wallet derivation path") + ":"), grid_row, 0
)
grid_maybe.addWidget(der_e, grid_row, 1)
grid_row += 1
if grid_row > 0: # only if above actually added widgets
self.addLayout(grid_maybe)
self.addStretch(1)
self.seed_warning = WWLabel("")
self.has_warning_message = bool(msg)
if self.has_warning_message:
self.seed_warning.setText(
seed_warning_msg(seed, bool(derivation), bool(passphrase))
)
self.addWidget(self.seed_warning)
def initialize_completer(self):
# Note that the wordlist for Electrum seeds is identical to the BIP39 wordlist
bip39_list = mnemonic.Mnemonic("english").wordlist
- old_list = old_mnemonic.words
+ old_list = old_mnemonic.wordlist
only_old_list = set(old_list) - set(bip39_list)
self.wordlist = bip39_list + list(only_old_list)
self.wordlist.sort()
class CompleterDelegate(QtWidgets.QStyledItemDelegate):
def initStyleOption(self, option, index):
super().initStyleOption(option, index)
# Some people complained that due to merging the two word lists,
# it is difficult to restore from a metal backup, as they planned
# to rely on the "4 letter prefixes are unique in bip39 word list" property.
# So we color words that are only in old list.
if option.text in only_old_list:
# yellow bg looks ~ok on both light/dark theme, regardless if (un)selected
option.backgroundBrush = ColorScheme.YELLOW.as_color(
background=True
)
self.completer = QtWidgets.QCompleter(self.wordlist)
delegate = CompleterDelegate(self.seed_e)
self.completer.popup().setItemDelegate(delegate)
self.seed_e.set_completer(self.completer)
def get_seed(self):
text = self.seed_e.text()
return " ".join(text.split())
_mnem = None
def on_edit(self):
may_clear_warning = not self.has_warning_message and self.editable
if self._mnem is None:
# cache the lang wordlist so it doesn't need to get loaded each time.
# This speeds up seed_type_name and Mnemonic.check
self._mnem = mnemonic.Mnemonic("english")
words = self.get_seed()
b = self.is_seed(words)
if not self.is_bip39:
t = mnemo.format_seed_type_name_for_ui(mnemo.seed_type_name(words))
label = _("Seed Type") + ": " + t if t else ""
if t and may_clear_warning and "bip39" in self.options:
match_set = mnemo.autodetect_seed_type(words)
if len(match_set) > 1 and mnemo.SeedType.BIP39 in match_set:
may_clear_warning = False
self.seed_warning.setText(
_(
"This seed is ambiguous and may also be interpreted as a"
" <b>BIP39</b> seed."
)
+ "<br/><br/>"
+ _(
"If you wish this seed to be interpreted as a BIP39 seed,"
" then use the Options button to force BIP39 interpretation"
" of this seed."
)
)
else:
is_valid = self._mnem.check(words)
status = "valid" if is_valid else "invalid"
label = f"BIP39 ({status})"
self.seed_type_label.setText(label)
self.parent.next_button.setEnabled(b)
if may_clear_warning:
self.seed_warning.setText("")
# Stop autocompletion if a previous word is not in the known list.
# The seed phrase must be a different language than english.
for word in self.get_seed().split(" ")[:-1]:
if word not in self.wordlist:
self.seed_e.disable_suggestions()
return
self.seed_e.enable_suggestions()
class KeysLayout(QtWidgets.QVBoxLayout):
def __init__(self, parent=None, title=None, is_valid=None, allow_multi=False):
QtWidgets.QVBoxLayout.__init__(self)
self.parent = parent
self.is_valid = is_valid
self.text_e = ScanQRTextEdit(allow_multi=allow_multi)
self.text_e.textChanged.connect(self.on_edit)
self.addWidget(WWLabel(title))
self.addWidget(self.text_e)
def get_text(self):
return self.text_e.text()
def on_edit(self):
b = self.is_valid(self.get_text())
self.parent.next_button.setEnabled(b)
class SeedDialog(WindowModalDialog):
def __init__(self, parent, seed, passphrase, derivation=None, seed_type=None):
WindowModalDialog.__init__(self, parent, (f"{PROJECT_NAME} - " + _("Seed")))
self.setMinimumWidth(400)
vbox = QtWidgets.QVBoxLayout(self)
title = _("Your wallet generation seed is:")
slayout = SeedLayout(
title=title,
seed=seed,
msg=True,
passphrase=passphrase,
editable=False,
derivation=derivation,
seed_type=seed_type,
)
vbox.addLayout(slayout)
vbox.addLayout(Buttons(CloseButton(self)))
File Metadata
Details
Attached
Mime Type
text/x-diff
Expires
Thu, May 22, 01:21 (19 h, 33 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
5866250
Default Alt Text
(61 KB)
Attached To
rABC Bitcoin ABC
Event Timeline
Log In to Comment