/tmp/bitcoin/src/util/bip32.cpp
Line | Count | Source |
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 | | bool ParseHDKeypath(const std::string& keypath_str, std::vector<uint32_t>& keypath) |
16 | 46 | { |
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 | 20 | } |
26 | 0 | return false; |
27 | 20 | } |
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 | 3 | return false; |
35 | 3 | } |
36 | 10 | path |= 0x80000000; |
37 | 10 | item = item.substr(0, item.size() - 1); // Drop the last character which is the hardened tick |
38 | 10 | } |
39 | | |
40 | | // Ensure this is only numbers |
41 | 167 | const auto number{ToIntegral<uint32_t>(item)}; |
42 | 167 | if (!number) { |
43 | 20 | return false; |
44 | 20 | } |
45 | 147 | path |= *number; |
46 | | |
47 | 147 | keypath.push_back(path); |
48 | 147 | first = false; |
49 | 147 | } |
50 | 23 | return true; |
51 | 46 | } |
52 | | |
53 | | std::string FormatHDKeypath(const std::vector<uint32_t>& path, bool apostrophe) |
54 | 292k | { |
55 | 292k | std::string ret; |
56 | 895k | for (auto i : path) { |
57 | 895k | ret += strprintf("/%i", (i << 1) >> 1); |
58 | 895k | if (i >> 31) ret += apostrophe ? '\'' : 'h'; |
59 | 895k | } |
60 | 292k | return ret; |
61 | 292k | } |
62 | | |
63 | | std::string WriteHDKeypath(const std::vector<uint32_t>& keypath, bool apostrophe) |
64 | 2.35k | { |
65 | 2.35k | return "m" + FormatHDKeypath(keypath, apostrophe); |
66 | 2.35k | } |