Bitcoin ABC  0.26.3
P2P Digital Currency
bip32.cpp
Go to the documentation of this file.
1 // Copyright (c) 2019 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <util/bip32.h>
6 
7 #include <tinyformat.h>
8 #include <util/strencodings.h>
9 
10 #include <cstdio>
11 #include <sstream>
12 
13 bool ParseHDKeypath(const std::string &keypath_str,
14  std::vector<uint32_t> &keypath) {
15  std::stringstream ss(keypath_str);
16  std::string item;
17  bool first = true;
18  while (std::getline(ss, item, '/')) {
19  if (item.compare("m") == 0) {
20  if (first) {
21  first = false;
22  continue;
23  }
24  return false;
25  }
26  // Finds whether it is hardened
27  uint32_t path = 0;
28  size_t pos = item.find("'");
29  if (pos != std::string::npos) {
30  // The hardened tick can only be in the last index of the string
31  if (pos != item.size() - 1) {
32  return false;
33  }
34  path |= 0x80000000;
35  // Drop the last character which is the hardened tick
36  item = item.substr(0, item.size() - 1);
37  }
38 
39  // Ensure this is only numbers
40  if (item.find_first_not_of("0123456789") != std::string::npos) {
41  return false;
42  }
43  uint32_t number;
44  if (!ParseUInt32(item, &number)) {
45  return false;
46  }
47  path |= number;
48 
49  keypath.push_back(path);
50  first = false;
51  }
52  return true;
53 }
54 
55 std::string FormatHDKeypath(const std::vector<uint32_t> &path) {
56  std::string ret;
57  for (auto i : path) {
58  ret += strprintf("/%i", (i << 1) >> 1);
59  if (i >> 31) {
60  ret += '\'';
61  }
62  }
63  return ret;
64 }
65 
66 std::string WriteHDKeypath(const std::vector<uint32_t> &keypath) {
67  return "m" + FormatHDKeypath(keypath);
68 }
bool ParseHDKeypath(const std::string &keypath_str, std::vector< uint32_t > &keypath)
Parse an HD keypaths like "m/7/0'/2000".
Definition: bip32.cpp:13
std::string FormatHDKeypath(const std::vector< uint32_t > &path)
Definition: bip32.cpp:55
std::string WriteHDKeypath(const std::vector< uint32_t > &keypath)
Write HD keypaths as strings.
Definition: bip32.cpp:66
bool ParseUInt32(const std::string &str, uint32_t *out)
Convert decimal string to unsigned 32-bit integer with strict parse error feedback.
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202