Kagome
Polkadot Runtime Engine in C++17
mnemonic.cpp
Go to the documentation of this file.
1 
7 
8 #include <codecvt>
9 #include <locale>
10 
11 #include <boost/algorithm/string.hpp>
13 #include "log/logger.hpp"
14 
15 namespace kagome::crypto::bip39 {
16 
17  namespace {
21  bool isValidUtf8(const std::string &s) {
22  // cannot replace for std::string_view for security reasons
23  std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t>
24  utf16conv;
25  try {
26  auto utf16 = utf16conv.from_bytes(s.data());
27  } catch (...) {
28  return false;
29  }
30  return true;
31  }
32  } // namespace
33 
34  outcome::result<Mnemonic> Mnemonic::parse(std::string_view phrase) {
35  if (phrase.empty() || !isValidUtf8(std::string(phrase))) {
37  }
38 
39  auto password_pos = phrase.find("///");
40  std::string_view mnemonic_list;
41  std::string_view password;
42  if (password_pos != std::string_view::npos) {
43  // need to normalize password utf8 nfkd
44  password = phrase.substr(password_pos + 3);
45  mnemonic_list = phrase.substr(0, password_pos);
46  } else {
47  mnemonic_list = phrase;
48  }
49 
50  if (mnemonic_list.find("/") != std::string_view::npos) {
51  log::createLogger("Mnemonic", "bip39")
52  ->error("junctions are not supported yet");
54  }
55 
56  // split word list into separate words
57  std::vector<std::string> word_list;
58  boost::split(word_list, mnemonic_list, boost::algorithm::is_space());
59 
60  Mnemonic mnemonic{std::move(word_list), std::string(password)};
61  return mnemonic;
62  //
63  }
64 } // namespace kagome::crypto::bip39
65 
68  switch (e) {
70  return "Mnemonic provided is not valid";
71  }
72  return "unknown MnemonicError";
73 }
static outcome::result< Mnemonic > parse(std::string_view phrase)
parse mnemonic from phrase
Definition: mnemonic.cpp:34
OUTCOME_CPP_DEFINE_CATEGORY(kagome::crypto::bip39, MnemonicError, e)
Definition: mnemonic.cpp:66
Logger createLogger(const std::string &tag)
Definition: logger.cpp:112