Debian Codegraph @

src/mnemonics/electrum-words.cpp

raw symbols SCIP
1 // Copyright (c) 2014-2022, The Monero Project
2 //
3 // All rights reserved.
4 //
5 // Redistribution and use in source and binary forms, with or without modification, are
6 // permitted provided that the following conditions are met:
7 //
8 // 1. Redistributions of source code must retain the above copyright notice, this list of
9 // conditions and the following disclaimer.
10 //
11 // 2. Redistributions in binary form must reproduce the above copyright notice, this list
12 // of conditions and the following disclaimer in the documentation and/or other
13 // materials provided with the distribution.
14 //
15 // 3. Neither the name of the copyright holder nor the names of its contributors may be
16 // used to endorse or promote products derived from this software without specific
17 // prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
20 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
22 // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26 // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
27 // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29 /*!
30 * \file electrum-words.cpp
31 *
32 * \brief Mnemonic seed generation and wallet restoration from them.
33 *
34 * This file and its header file are for translating Electrum-style word lists
35 * into their equivalent byte representations for cross-compatibility with
36 * that method of "backing up" one's wallet keys.
37 */
38
39 #include <string>
40 #include <cstdint>
41 #include <vector>
42 #include <unordered_map>
43 #include "wipeable_string.h"
44 #include "misc_language.h"
45 #include "int-util.h"
46 #include "mnemonics/electrum-words.h"
47 #include <boost/crc.hpp>
48
49 #include "chinese_simplified.h"
50 #include "english.h"
51 #include "dutch.h"
52 #include "french.h"
53 #include "italian.h"
54 #include "german.h"
55 #include "spanish.h"
56 #include "portuguese.h"
57 #include "japanese.h"
58 #include "russian.h"
59 #include "esperanto.h"
60 #include "lojban.h"
61 #include "english_old.h"
62 #include "language_base.h"
63 #include "singleton.h"
64
65 #undef MONERO_DEFAULT_LOG_CATEGORY
66 #define MONERO_DEFAULT_LOG_CATEGORY "mnemonic"
67
68 namespace crypto
69 {
70 namespace ElectrumWords
71 {
72 std::vector<const Language::Base*> get_language_list();
73 }
74 }
75
76 namespace
77 {
78 uint32_t create_checksum_index(const std::vector<epee::wipeable_string> &word_list,
79 const Language::Base *language);
80 bool checksum_test(std::vector<epee::wipeable_string> seed, const Language::Base *language);
81
82 /*!
83 * \brief Finds the word list that contains the seed words and puts the indices
84 * where matches occured in matched_indices.
85 * \param seed List of words to match.
86 * \param has_checksum The seed has a checksum word (maybe not checked).
87 * \param matched_indices The indices where the seed words were found are added to this.
88 * \param language Language instance pointer to write to after it is found.
89 * \return true if all the words were present in some language false if not.
90 */
91 bool find_seed_language(const std::vector<epee::wipeable_string> &seed,
92 bool has_checksum, std::vector<uint32_t> &matched_indices, Language::Base **language)
93 {
94 // If there's a new language added, add an instance of it here.
95 std::vector<Language::Base*> language_instances({
96 Language::Singleton<Language::Chinese_Simplified>::instance(),
97 Language::Singleton<Language::English>::instance(),
98 Language::Singleton<Language::Dutch>::instance(),
99 Language::Singleton<Language::French>::instance(),
100 Language::Singleton<Language::Spanish>::instance(),
101 Language::Singleton<Language::German>::instance(),
102 Language::Singleton<Language::Italian>::instance(),
103 Language::Singleton<Language::Portuguese>::instance(),
104 Language::Singleton<Language::Japanese>::instance(),
105 Language::Singleton<Language::Russian>::instance(),
106 Language::Singleton<Language::Esperanto>::instance(),
107 Language::Singleton<Language::Lojban>::instance(),
108 Language::Singleton<Language::EnglishOld>::instance()
109 });
110 Language::Base *fallback = NULL;
111
112 std::vector<epee::wipeable_string>::const_iterator it2;
113 matched_indices.reserve(seed.size());
114
115 // Iterate through all the languages and find a match
116 for (std::vector<Language::Base*>::iterator it1 = language_instances.begin();
117 it1 != language_instances.end(); it1++)
118 {
119 const std::unordered_map<epee::wipeable_string, uint32_t, Language::WordHash, Language::WordEqual> &word_map = (*it1)->get_word_map();
120 const std::unordered_map<epee::wipeable_string, uint32_t, Language::WordHash, Language::WordEqual> &trimmed_word_map = (*it1)->get_trimmed_word_map();
121 // To iterate through seed words
122 bool full_match = true;
123
124 epee::wipeable_string trimmed_word;
125 // Iterate through all the words and see if they're all present
126 for (it2 = seed.begin(); it2 != seed.end(); it2++)
127 {
128 if (has_checksum)
129 {
130 trimmed_word = Language::utf8prefix(*it2, (*it1)->get_unique_prefix_length());
131 // Use the trimmed words and map
132 if (trimmed_word_map.count(trimmed_word) == 0)
133 {
134 full_match = false;
135 break;
136 }
137 matched_indices.push_back(trimmed_word_map.at(trimmed_word));
138 }
139 else
140 {
141 if (word_map.count(*it2) == 0)
142 {
143 full_match = false;
144 break;
145 }
146 matched_indices.push_back(word_map.at(*it2));
147 }
148 }
149 if (full_match)
150 {
151 // if we were using prefix only, and we have a checksum, check it now
152 // to avoid false positives due to prefix set being too common
153 if (has_checksum)
154 if (!checksum_test(seed, *it1))
155 {
156 fallback = *it1;
157 full_match = false;
158 }
159 }
160 if (full_match)
161 {
162 *language = *it1;
163 MINFO("Full match for language " << (*language)->get_english_language_name());
164 return true;
165 }
166 // Some didn't match. Clear the index array.
167 memwipe(matched_indices.data(), matched_indices.size() * sizeof(matched_indices[0]));
168 matched_indices.clear();
169 }
170
171 // if we get there, we've not found a good match, but we might have a fallback,
172 // if we detected a match which did not fit the checksum, which might be a badly
173 // typed/transcribed seed in the right language
174 if (fallback)
175 {
176 *language = fallback;
177 MINFO("Fallback match for language " << (*language)->get_english_language_name());
178 return true;
179 }
180
181 MINFO("No match found");
182 memwipe(matched_indices.data(), matched_indices.size() * sizeof(matched_indices[0]));
183 return false;
184 }
185
186 /*!
187 * \brief Creates a checksum index in the word list array on the list of words.
188 * \param word_list Vector of words
189 * \param unique_prefix_length the prefix length of each word to use for checksum
190 * \return Checksum index
191 */
192 uint32_t create_checksum_index(const std::vector<epee::wipeable_string> &word_list,
193 const Language::Base *language)
194 {
195 epee::wipeable_string trimmed_words = "", word;
196
197 const auto &trimmed_word_map = language->get_trimmed_word_map();
198 const uint32_t unique_prefix_length = language->get_unique_prefix_length();
199 for (std::vector<epee::wipeable_string>::const_iterator it = word_list.begin(); it != word_list.end(); it++)
200 {
201 word = Language::utf8prefix(*it, unique_prefix_length);
202 auto it2 = trimmed_word_map.find(word);
203 if (it2 == trimmed_word_map.end())
204 throw std::runtime_error("Word \"" + std::string(word.data(), word.size()) + "\" not found in trimmed word map in " + language->get_english_language_name());
205 trimmed_words += it2->first;
206 }
207 boost::crc_32_type result;
208 result.process_bytes(trimmed_words.data(), trimmed_words.length());
209 return result.checksum() % word_list.size();
210 }
211
212 /*!
213 * \brief Does the checksum test on the seed passed.
214 * \param seed Vector of seed words
215 * \param unique_prefix_length the prefix length of each word to use for checksum
216 * \return True if the test passed false if not.
217 */
218 bool checksum_test(std::vector<epee::wipeable_string> seed, const Language::Base *language)
219 {
220 if (seed.empty())
221 return false;
222 // The last word is the checksum.
223 epee::wipeable_string last_word = seed.back();
224 seed.pop_back();
225
226 const uint32_t unique_prefix_length = language->get_unique_prefix_length();
227
228 auto idx = create_checksum_index(seed, language);
229 epee::wipeable_string checksum = seed[idx];
230
231 epee::wipeable_string trimmed_checksum = checksum.length() > unique_prefix_length ? Language::utf8prefix(checksum, unique_prefix_length) :
232 checksum;
233 epee::wipeable_string trimmed_last_word = last_word.length() > unique_prefix_length ? Language::utf8prefix(last_word, unique_prefix_length) :
234 last_word;
235 bool ret = Language::WordEqual()(trimmed_checksum, trimmed_last_word);
236 MINFO("Checksum is " << (ret ? "valid" : "invalid"));
237 return ret;
238 }
239 }
240
241 /*!
242 * \namespace crypto
243 *
244 * \brief crypto namespace.
245 */
246 namespace crypto
247 {
248 /*!
249 * \namespace crypto::ElectrumWords
250 *
251 * \brief Mnemonic seed word generation and wallet restoration helper functions.
252 */
253 namespace ElectrumWords
254 {
255 /*!
256 * \brief Converts seed words to bytes (secret key).
257 * \param words String containing the words separated by spaces.
258 * \param dst To put the secret data restored from the words.
259 * \param len The number of bytes to expect, 0 if unknown
260 * \param duplicate If true and len is not zero, we accept half the data, and duplicate it
261 * \param language_name Language of the seed as found gets written here.
262 * \return false if not a multiple of 3 words, or if word is not in the words list
263 */
264 bool words_to_bytes(const epee::wipeable_string &words, epee::wipeable_string& dst, size_t len, bool duplicate,
265 std::string &language_name)
266 {
267 std::vector<epee::wipeable_string> seed;
268
269 words.split(seed);
270
271 if (len % 4)
272 {
273 MERROR("Invalid seed: not a multiple of 4");
274 return false;
275 }
276
277 bool has_checksum = true;
278 if (len)
279 {
280 // error on non-compliant word list
281 const size_t expected = len * 8 * 3 / 32;
282 if (seed.size() != expected/2 && seed.size() != expected &&
283 seed.size() != expected + 1)
284 {
285 MERROR("Invalid seed: unexpected number of words");
286 return false;
287 }
288
289 // If it is seed with a checksum.
290 has_checksum = seed.size() == (expected + 1);
291 }
292
293 std::vector<uint32_t> matched_indices;
294 auto wiper = epee::misc_utils::create_scope_leave_handler([&](){memwipe(matched_indices.data(), matched_indices.size() * sizeof(matched_indices[0]));});
295 Language::Base *language;
296 if (!find_seed_language(seed, has_checksum, matched_indices, &language))
297 {
298 MERROR("Invalid seed: language not found");
299 return false;
300 }
301 language_name = language->get_language_name();
302 uint32_t word_list_length = language->get_word_list().size();
303
304 if (has_checksum)
305 {
306 if (!checksum_test(seed, language))
307 {
308 // Checksum fail
309 MERROR("Invalid seed: invalid checksum");
310 return false;
311 }
312 seed.pop_back();
313 }
314
315 for (unsigned int i=0; i < seed.size() / 3; i++)
316 {
317 uint32_t w[4];
318 w[1] = matched_indices[i*3];
319 w[2] = matched_indices[i*3 + 1];
320 w[3] = matched_indices[i*3 + 2];
321
322 w[0]= w[1] + word_list_length * (((word_list_length - w[1]) + w[2]) % word_list_length) +
323 word_list_length * word_list_length * (((word_list_length - w[2]) + w[3]) % word_list_length);
324
325 if (!(w[0]% word_list_length == w[1]))
326 {
327 memwipe(w, sizeof(w));
328 MERROR("Invalid seed: mumble mumble");
329 return false;
330 }
331
332 w[0] = SWAP32LE(w[0]);
333 dst.append((const char*)&w[0], 4); // copy 4 bytes to position
334 memwipe(w, sizeof(w));
335 }
336
337 if (len > 0 && duplicate)
338 {
339 const size_t expected = len * 3 / 32;
340 if (seed.size() == expected/2)
341 {
342 dst.append(dst.data(), dst.size()); // if electrum 12-word seed, duplicate
343 }
344 }
345
346 return true;
347 }
348
349 /*!
350 * \brief Converts seed words to bytes (secret key).
351 * \param words String containing the words separated by spaces.
352 * \param dst To put the secret key restored from the words.
353 * \param language_name Language of the seed as found gets written here.
354 * \return false if not a multiple of 3 words, or if word is not in the words list
355 */
356 bool words_to_bytes(const epee::wipeable_string &words, crypto::secret_key& dst,
357 std::string &language_name)
358 {
359 epee::wipeable_string s;
360 if (!words_to_bytes(words, s, sizeof(dst), true, language_name))
361 {
362 MERROR("Invalid seed: failed to convert words to bytes");
363 return false;
364 }
365 if (s.size() != sizeof(dst))
366 {
367 MERROR("Invalid seed: wrong output size");
368 return false;
369 }
370 dst = *(const crypto::secret_key*)s.data();
371 return true;
372 }
373
374 /*!
375 * \brief Converts bytes (secret key) to seed words.
376 * \param src Secret key
377 * \param words Space delimited concatenated words get written here.
378 * \param language_name Seed language name
379 * \return true if successful false if not. Unsuccessful if wrong key size.
380 */
381 bool bytes_to_words(const char *src, size_t len, epee::wipeable_string& words,
382 const std::string &language_name)
383 {
384
385 if (len % 4 != 0 || len == 0) return false;
386
387 const Language::Base *language = NULL;
388 const std::vector<const Language::Base*> language_list = crypto::ElectrumWords::get_language_list();
389 for (const Language::Base *l: language_list)
390 {
391 if (language_name == l->get_language_name() || language_name == l->get_english_language_name())
392 language = l;
393 }
394 if (!language)
395 {
396 return false;
397 }
398 const std::vector<std::string> &word_list = language->get_word_list();
399 // To store the words for random access to add the checksum word later.
400 std::vector<epee::wipeable_string> words_store;
401
402 uint32_t word_list_length = word_list.size();
403 // 4 bytes -> 3 words. 8 digits base 16 -> 3 digits base 1626
404 for (unsigned int i=0; i < len/4; i++, words.push_back(' '))
405 {
406 uint32_t w[4];
407
408 w[0] = SWAP32LE(*(const uint32_t*)(src + (i * 4)));
409
410 w[1] = w[0] % word_list_length;
411 w[2] = ((w[0] / word_list_length) + w[1]) % word_list_length;
412 w[3] = (((w[0] / word_list_length) / word_list_length) + w[2]) % word_list_length;
413
414 words += word_list[w[1]];
415 words += ' ';
416 words += word_list[w[2]];
417 words += ' ';
418 words += word_list[w[3]];
419
420 words_store.push_back(word_list[w[1]]);
421 words_store.push_back(word_list[w[2]]);
422 words_store.push_back(word_list[w[3]]);
423
424 memwipe(w, sizeof(w));
425 }
426
427 words += words_store[create_checksum_index(words_store, language)];
428 return true;
429 }
430
431 bool bytes_to_words(const crypto::secret_key& src, epee::wipeable_string& words,
432 const std::string &language_name)
433 {
434 return bytes_to_words(src.data, sizeof(src), words, language_name);
435 }
436
437 std::vector<const Language::Base*> get_language_list()
438 {
439 static const std::vector<const Language::Base*> language_instances({
440 Language::Singleton<Language::German>::instance(),
441 Language::Singleton<Language::English>::instance(),
442 Language::Singleton<Language::Spanish>::instance(),
443 Language::Singleton<Language::French>::instance(),
444 Language::Singleton<Language::Italian>::instance(),
445 Language::Singleton<Language::Dutch>::instance(),
446 Language::Singleton<Language::Portuguese>::instance(),
447 Language::Singleton<Language::Russian>::instance(),
448 Language::Singleton<Language::Japanese>::instance(),
449 Language::Singleton<Language::Chinese_Simplified>::instance(),
450 Language::Singleton<Language::Esperanto>::instance(),
451 Language::Singleton<Language::Lojban>::instance()
452 });
453 return language_instances;
454 }
455
456 /*!
457 * \brief Gets a list of seed languages that are supported.
458 * \param languages The vector is set to the list of languages.
459 */
460 void get_language_list(std::vector<std::string> &languages, bool english)
461 {
462 const std::vector<const Language::Base*> language_instances = get_language_list();
463 for (std::vector<const Language::Base*>::const_iterator it = language_instances.begin();
464 it != language_instances.end(); it++)
465 {
466 languages.push_back(english ? (*it)->get_english_language_name() : (*it)->get_language_name());
467 }
468 }
469
470 /*!
471 * \brief Tells if the seed passed is an old style seed or not.
472 * \param seed The seed to check (a space delimited concatenated word list)
473 * \return true if the seed passed is a old style seed false if not.
474 */
475 bool get_is_old_style_seed(const epee::wipeable_string &seed)
476 {
477 std::vector<epee::wipeable_string> word_list;
478 seed.split(word_list);
479 return word_list.size() != (seed_length + 1);
480 }
481
482 std::string get_english_name_for(const std::string &name)
483 {
484 const std::vector<const Language::Base*> language_instances = get_language_list();
485 for (std::vector<const Language::Base*>::const_iterator it = language_instances.begin();
486 it != language_instances.end(); it++)
487 {
488 if ((*it)->get_language_name() == name)
489 return (*it)->get_english_language_name();
490 }
491 return "<language not found>";
492 }
493
494 bool is_valid_language(const std::string &language)
495 {
496 const std::vector<const Language::Base*> language_instances = get_language_list();
497 for (std::vector<const Language::Base*>::const_iterator it = language_instances.begin(); it != language_instances.end(); it++)
498 if ((*it)->get_english_language_name() == language || (*it)->get_language_name() == language)
499 return true;
500 return false;
501 }
502 }
503
504 }