Branch data Line data Source code
1 : : // Copyright (c) 2019-present 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 <cstdint>
11 : : #include <cstdio>
12 : : #include <optional>
13 : : #include <sstream>
14 : :
15 : 46 : bool ParseHDKeypath(const std::string& keypath_str, std::vector<uint32_t>& keypath)
16 : : {
17 : 46 : std::stringstream ss(keypath_str);
18 : 46 : std::string item;
19 : 46 : bool first = true;
20 [ + - + + ]: 213 : while (std::getline(ss, item, '/')) {
21 [ + + ]: 190 : if (item.compare("m") == 0) {
22 [ + - ]: 20 : if (first) {
23 : 20 : first = false;
24 : 20 : continue;
25 : : }
26 : : return false;
27 : : }
28 : : // Finds whether it is hardened
29 : 170 : uint32_t path = 0;
30 : 170 : size_t pos = item.find('\'');
31 [ + + ]: 170 : if (pos != std::string::npos) {
32 : : // The hardened tick can only be in the last index of the string
33 [ - + + + ]: 13 : if (pos != item.size() - 1) {
34 : : return false;
35 : : }
36 : 10 : path |= 0x80000000;
37 [ + - ]: 10 : item = item.substr(0, item.size() - 1); // Drop the last character which is the hardened tick
38 : : }
39 : :
40 : : // Ensure this is only numbers
41 [ - + ]: 167 : const auto number{ToIntegral<uint32_t>(item)};
42 [ + + ]: 167 : if (!number) {
43 : : return false;
44 : : }
45 [ + - ]: 147 : path |= *number;
46 : :
47 [ + - ]: 147 : keypath.push_back(path);
48 : : first = false;
49 : : }
50 : : return true;
51 : 46 : }
52 : :
53 : 289895 : std::string FormatHDKeypath(const std::vector<uint32_t>& path, bool apostrophe)
54 : : {
55 : 289895 : std::string ret;
56 [ + + ]: 1174515 : for (auto i : path) {
57 [ + - ]: 1769240 : ret += strprintf("/%i", (i << 1) >> 1);
58 [ + + + + ]: 1446039 : if (i >> 31) ret += apostrophe ? '\'' : 'h';
59 : : }
60 : 289895 : return ret;
61 : 0 : }
62 : :
63 : 2394 : std::string WriteHDKeypath(const std::vector<uint32_t>& keypath, bool apostrophe)
64 : : {
65 [ + - ]: 4788 : return "m" + FormatHDKeypath(keypath, apostrophe);
66 : : }
|