Debian Codegraph @

monero/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
69 {
70 uint32_t create_checksum_index(const std::vector<epee::wipeable_string> &word_list,
71 const Language::Base *language);
72 bool checksum_test(std::vector<epee::wipeable_string> seed, const Language::Base *language);
73
74 /*!
75 * \brief Finds the word list that contains the seed words and puts the indices
76 * where matches occured in matched_indices.
77 * \param seed List of words to match.
78 * \param has_checksum The seed has a checksum word (maybe not checked).
79 * \param matched_indices The indices where the seed words were found are added to this.
80 * \param language Language instance pointer to write to after it is found.
81 * \return true if all the words were present in some language false if not.
82 */
83 bool find_seed_language(const std::vector<epee::wipeable_string> &seed,
84 bool has_checksum, std::vector<uint32_t> &matched_indices, Language::Base **language)
85 {
86 // If there's a new language added, add an instance of it here.
87 std::vector<Language::Base*> language_instances({
88 Language::Singleton<Language::Chinese_Simplified>::instance(),
89 Language::Singleton<Language::English>::instance(),
90 Language::Singleton<Language::Dutch>::instance(),
91 Language::Singleton<Language::French>::instance(),
92 Language::Singleton<Language::Spanish>::instance(),
93 Language::Singleton<Language::German>::instance(),
94 Language::Singleton<Language::Italian>::instance(),
95 Language::Singleton<Language::Portuguese>::instance(),
96 Language::Singleton<Language::Japanese>::instance(),
97 Language::Singleton<Language::Russian>::instance(),
98 Language::Singleton<Language::Esperanto>::instance(),
99 Language::Singleton<Language::Lojban>::instance(),
100 Language::Singleton<Language::EnglishOld>::instance()
101 });
102 Language::Base *fallback = NULL;
103
104 std::vector<epee::wipeable_string>::const_iterator it2;
105 matched_indices.reserve(seed.size());
106
107 // Iterate through all the languages and find a match
108 for (std::vector<Language::Base*>::iterator it1 = language_instances.begin();
109 it1 != language_instances.end(); it1++)
110 {
111 const std::unordered_map<epee::wipeable_string, uint32_t, Language::WordHash, Language::WordEqual> &word_map = (*it1)->get_word_map();
112 const std::unordered_map<epee::wipeable_string, uint32_t, Language::WordHash, Language::WordEqual> &trimmed_word_map = (*it1)->get_trimmed_word_map();
113 // To iterate through seed words
114 bool full_match = true;
115
116 epee::wipeable_string trimmed_word;
117 // Iterate through all the words and see if they're all present
118 for (it2 = seed.begin(); it2 != seed.end(); it2++)
119 {
120 if (has_checksum)
121 {
122 trimmed_word = Language::utf8prefix(*it2, (*it1)->get_unique_prefix_length());
123 // Use the trimmed words and map
124 if (trimmed_word_map.count(trimmed_word) == 0)
125 {
126 full_match = false;
127 break;
128 }
129 matched_indices.push_back(trimmed_word_map.at(trimmed_word));
130 }
131 else
132 {
133 if (word_map.count(*it2) == 0)
134 {
135 full_match = false;
136 break;
137 }
138 matched_indices.push_back(word_map.at(*it2));
139 }
140 }
141 if (full_match)
142 {
143 // if we were using prefix only, and we have a checksum, check it now
144 // to avoid false positives due to prefix set being too common
145 if (has_checksum)
146 if (!checksum_test(seed, *it1))
147 {
148 fallback = *it1;
149 full_match = false;
150 }
151 }
152 if (full_match)
153 {
154 *language = *it1;
155 MINFO("Full match for language " << (*language)->get_english_language_name());
156 return true;
157 }
158 // Some didn't match. Clear the index array.
159 memwipe(matched_indices.data(), matched_indices.size() * sizeof(matched_indices[0]));
160 matched_indices.clear();
161 }
162
163 // if we get there, we've not found a good match, but we might have a fallback,
164 // if we detected a match which did not fit the checksum, which might be a badly
165 // typed/transcribed seed in the right language
166 if (fallback)
167 {
168 *language = fallback;
169 MINFO("Fallback match for language " << (*language)->get_english_language_name());
170 return true;
171 }
172
173 MINFO("No match found");
174 memwipe(matched_indices.data(), matched_indices.size() * sizeof(matched_indices[0]));
175 return false;
176 }
177
178 /*!
179 * \brief Creates a checksum index in the word list array on the list of words.
180 * \param word_list Vector of words
181 * \param unique_prefix_length the prefix length of each word to use for checksum
182 * \return Checksum index
183 */
184 uint32_t create_checksum_index(const std::vector<epee::wipeable_string> &word_list,
185 const Language::Base *language)
186 {
187 epee::wipeable_string trimmed_words = "", word;
188
189 const auto &trimmed_word_map = language->get_trimmed_word_map();
190 const uint32_t unique_prefix_length = language->get_unique_prefix_length();
191 for (std::vector<epee::wipeable_string>::const_iterator it = word_list.begin(); it != word_list.end(); it++)
192 {
193 word = Language::utf8prefix(*it, unique_prefix_length);
194 auto it2 = trimmed_word_map.find(word);
195 if (it2 == trimmed_word_map.end())
196 throw std::runtime_error("Word \"" + std::string(word.data(), word.size()) + "\" not found in trimmed word map in " + language->get_english_language_name());
197 trimmed_words += it2->first;
198 }
199 boost::crc_32_type result;
200 result.process_bytes(trimmed_words.data(), trimmed_words.length());
201 return result.checksum() % word_list.size();
202 }
203
204 /*!
205 * \brief Does the checksum test on the seed passed.
206 * \param seed Vector of seed words
207 * \param unique_prefix_length the prefix length of each word to use for checksum
208 * \return True if the test passed false if not.
209 */
210 bool checksum_test(std::vector<epee::wipeable_string> seed, const Language::Base *language)
211 {
212 if (seed.empty())
213 return false;
214 // The last word is the checksum.
215 epee::wipeable_string last_word = seed.back();
216 seed.pop_back();
217
218 const uint32_t unique_prefix_length = language->get_unique_prefix_length();
219
220 auto idx = create_checksum_index(seed, language);
221 epee::wipeable_string checksum = seed[idx];
222
223 epee::wipeable_string trimmed_checksum = checksum.length() > unique_prefix_length ? Language::utf8prefix(checksum, unique_prefix_length) :
224 checksum;
225 epee::wipeable_string trimmed_last_word = last_word.length() > unique_prefix_length ? Language::utf8prefix(last_word, unique_prefix_length) :
226 last_word;
227 bool ret = Language::WordEqual()(trimmed_checksum, trimmed_last_word);
228 MINFO("Checksum is " << (ret ? "valid" : "invalid"));
229 return ret;
230 }
231 }
232
233 /*!
234 * \namespace crypto
235 *
236 * \brief crypto namespace.
237 */
238 namespace crypto
239 {
240 /*!
241 * \namespace crypto::ElectrumWords
242 *
243 * \brief Mnemonic seed word generation and wallet restoration helper functions.
244 */
245 namespace ElectrumWords
246 {
247 /*!
248 * \brief Converts seed words to bytes (secret key).
249 * \param words String containing the words separated by spaces.
250 * \param dst To put the secret data restored from the words.
251 * \param len The number of bytes to expect, 0 if unknown
252 * \param duplicate If true and len is not zero, we accept half the data, and duplicate it
253 * \param language_name Language of the seed as found gets written here.
254 * \return false if not a multiple of 3 words, or if word is not in the words list
255 */
256 bool words_to_bytes(const epee::wipeable_string &words, epee::wipeable_string& dst, size_t len, bool duplicate,
257 std::string &language_name)
258 {
259 std::vector<epee::wipeable_string> seed;
260
261 words.split(seed);
262
263 if (len % 4)
264 {
265 MERROR("Invalid seed: not a multiple of 4");
266 return false;
267 }
268
269 bool has_checksum = true;
270 if (len)
271 {
272 // error on non-compliant word list
273 const size_t expected = len * 8 * 3 / 32;
274 if (seed.size() != expected/2 && seed.size() != expected &&
275 seed.size() != expected + 1)
276 {
277 MERROR("Invalid seed: unexpected number of words");
278 return false;
279 }
280
281 // If it is seed with a checksum.
282 has_checksum = seed.size() == (expected + 1);
283 }
284
285 std::vector<uint32_t> matched_indices;
286 auto wiper = epee::misc_utils::create_scope_leave_handler([&](){memwipe(matched_indices.data(), matched_indices.size() * sizeof(matched_indices[0]));});
287 Language::Base *language;
288 if (!find_seed_language(seed, has_checksum, matched_indices, &language))
289 {
290 MERROR("Invalid seed: language not found");
291 return false;
292 }
293 language_name = language->get_language_name();
294 uint32_t word_list_length = language->get_word_list().size();
295
296 if (has_checksum)
297 {
298 if (!checksum_test(seed, language))
299 {
300 // Checksum fail
301 MERROR("Invalid seed: invalid checksum");
302 return false;
303 }
304 seed.pop_back();
305 }
306
307 for (unsigned int i=0; i < seed.size() / 3; i++)
308 {
309 uint32_t w[4];
310 w[1] = matched_indices[i*3];
311 w[2] = matched_indices[i*3 + 1];
312 w[3] = matched_indices[i*3 + 2];
313
314 w[0]= w[1] + word_list_length * (((word_list_length - w[1]) + w[2]) % word_list_length) +
315 word_list_length * word_list_length * (((word_list_length - w[2]) + w[3]) % word_list_length);
316
317 if (!(w[0]% word_list_length == w[1]))
318 {
319 memwipe(w, sizeof(w));
320 MERROR("Invalid seed: mumble mumble");
321 return false;
322 }
323
324 w[0] = SWAP32LE(w[0]);
325 dst.append((const char*)&w[0], 4); // copy 4 bytes to position
326 memwipe(w, sizeof(w));
327 }
328
329 if (len > 0 && duplicate)
330 {
331 const size_t expected = len * 3 / 32;
332 if (seed.size() == expected/2)
333 {
334 dst.append(dst.data(), dst.size()); // if electrum 12-word seed, duplicate
335 }
336 }
337
338 return true;
339 }
340
341 /*!
342 * \brief Converts seed words to bytes (secret key).
343 * \param words String containing the words separated by spaces.
344 * \param dst To put the secret key restored from the words.
345 * \param language_name Language of the seed as found gets written here.
346 * \return false if not a multiple of 3 words, or if word is not in the words list
347 */
348 bool words_to_bytes(const epee::wipeable_string &words, crypto::secret_key& dst,
349 std::string &language_name)
350 {
351 epee::wipeable_string s;
352 if (!words_to_bytes(words, s, sizeof(dst), true, language_name))
353 {
354 MERROR("Invalid seed: failed to convert words to bytes");
355 return false;
356 }
357 if (s.size() != sizeof(dst))
358 {
359 MERROR("Invalid seed: wrong output size");
360 return false;
361 }
362 dst = *(const crypto::secret_key*)s.data();
363 return true;
364 }
365
366 /*!
367 * \brief Converts bytes (secret key) to seed words.
368 * \param src Secret key
369 * \param words Space delimited concatenated words get written here.
370 * \param language_name Seed language name
371 * \return true if successful false if not. Unsuccessful if wrong key size.
372 */
373 bool bytes_to_words(const char *src, size_t len, epee::wipeable_string& words,
374 const std::string &language_name)
375 {
376
377 if (len % 4 != 0 || len == 0) return false;
378
379 const Language::Base *language = NULL;
380 const std::vector<const Language::Base*> language_list = crypto::ElectrumWords::get_language_list();
381 for (const Language::Base *l: language_list)
382 {
383 if (language_name == l->get_language_name() || language_name == l->get_english_language_name())
384 language = l;
385 }
386 if (!language)
387 {
388 return false;
389 }
390 const std::vector<std::string> &word_list = language->get_word_list();
391 // To store the words for random access to add the checksum word later.
392 std::vector<epee::wipeable_string> words_store;
393
394 uint32_t word_list_length = word_list.size();
395 // 4 bytes -> 3 words. 8 digits base 16 -> 3 digits base 1626
396 for (unsigned int i=0; i < len/4; i++, words.push_back(' '))
397 {
398 uint32_t w[4];
399
400 w[0] = SWAP32LE(*(const uint32_t*)(src + (i * 4)));
401
402 w[1] = w[0] % word_list_length;
403 w[2] = ((w[0] / word_list_length) + w[1]) % word_list_length;
404 w[3] = (((w[0] / word_list_length) / word_list_length) + w[2]) % word_list_length;
405
406 words += word_list[w[1]];
407 words += ' ';
408 words += word_list[w[2]];
409 words += ' ';
410 words += word_list[w[3]];
411
412 words_store.push_back(word_list[w[1]]);
413 words_store.push_back(word_list[w[2]]);
414 words_store.push_back(word_list[w[3]]);
415
416 memwipe(w, sizeof(w));
417 }
418
419 words += words_store[create_checksum_index(words_store, language)];
420 return true;
421 }
422
423 bool bytes_to_words(const crypto::secret_key& src, epee::wipeable_string& words,
424 const std::string &language_name)
425 {
426 return bytes_to_words(src.data, sizeof(src), words, language_name);
427 }
428
429 std::vector<const Language::Base*> get_language_list()
430 {
431 static const std::vector<const Language::Base*> language_instances({
432 Language::Singleton<Language::German>::instance(),
433 Language::Singleton<Language::English>::instance(),
434 Language::Singleton<Language::Spanish>::instance(),
435 Language::Singleton<Language::French>::instance(),
436 Language::Singleton<Language::Italian>::instance(),
437 Language::Singleton<Language::Dutch>::instance(),
438 Language::Singleton<Language::Portuguese>::instance(),
439 Language::Singleton<Language::Russian>::instance(),
440 Language::Singleton<Language::Japanese>::instance(),
441 Language::Singleton<Language::Chinese_Simplified>::instance(),
442 Language::Singleton<Language::Esperanto>::instance(),
443 Language::Singleton<Language::Lojban>::instance()
444 });
445 return language_instances;
446 }
447
448 /*!
449 * \brief Gets a list of seed languages that are supported.
450 * \param languages The vector is set to the list of languages.
451 */
452 void get_language_list(std::vector<std::string> &languages, bool english)
453 {
454 const std::vector<const Language::Base*> language_instances = get_language_list();
455 for (std::vector<const Language::Base*>::const_iterator it = language_instances.begin();
456 it != language_instances.end(); it++)
457 {
458 languages.push_back(english ? (*it)->get_english_language_name() : (*it)->get_language_name());
459 }
460 }
461
462 /*!
463 * \brief Tells if the seed passed is an old style seed or not.
464 * \param seed The seed to check (a space delimited concatenated word list)
465 * \return true if the seed passed is a old style seed false if not.
466 */
467 bool get_is_old_style_seed(const epee::wipeable_string &seed)
468 {
469 std::vector<epee::wipeable_string> word_list;
470 seed.split(word_list);
471 return word_list.size() != (seed_length + 1);
472 }
473
474 std::string get_english_name_for(const std::string &name)
475 {
476 const std::vector<const Language::Base*> language_instances = get_language_list();
477 for (std::vector<const Language::Base*>::const_iterator it = language_instances.begin();
478 it != language_instances.end(); it++)
479 {
480 if ((*it)->get_language_name() == name)
481 return (*it)->get_english_language_name();
482 }
483 return "<language not found>";
484 }
485
486 bool is_valid_language(const std::string &language)
487 {
488 const std::vector<const Language::Base*> language_instances = get_language_list();
489 for (std::vector<const Language::Base*>::const_iterator it = language_instances.begin(); it != language_instances.end(); it++)
490 if ((*it)->get_english_language_name() == language || (*it)->get_language_name() == language)
491 return true;
492 return false;
493 }
494 }
495
496 }