Repository navigation
Expand file tree
/
Copy pathbip32.cpp
More file actions
82 lines (72 loc) · 2.41 KB
/
Copy pathbip32.cpp
File metadata and controls
82 lines (72 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Copyright (c) 2019-present The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <util/bip32.h>
#include <tinyformat.h>
#include <util/strencodings.h>
#include <algorithm>
#include <cstdint>
#include <optional>
#include <span>
#include <sstream>
#include <string_view>
util::Expected<KeyPathElement, std::string> ParseKeyPathElement(std::span<const char> elem)
{
const std::string_view raw{elem.begin(), elem.end()};
if (elem.empty()) {
return util::Unexpected{strprintf("Key path value '%s' is not valid", raw)};
}
bool is_hardened = false;
const char last = elem.back();
if (last == '\'' || last == 'h') {
elem = elem.first(elem.size() - 1);
is_hardened = true;
}
const auto number{ToIntegral<uint32_t>(std::string_view{elem.begin(), elem.end()})};
if (!number) {
return util::Unexpected{strprintf("Key path value '%s' is not a valid uint32", raw)};
}
if (*number >= BIP32_HARDENED_FLAG) {
return util::Unexpected{strprintf("Key path value %u is out of range", *number)};
}
return KeyPathElement{*number, is_hardened};
}
bool ParseHDKeypath(const std::string& keypath_str, std::vector<uint32_t>& keypath)
{
std::stringstream ss(keypath_str);
std::string item;
bool first = true;
while (std::getline(ss, item, '/') || std::getline(ss, item, 'h')) {
if (item.compare("m") == 0) {
if (first) {
first = false;
continue;
}
return false;
}
const auto parsed{ParseKeyPathElement(std::span<const char>{item.data(), item.size()})};
if (!parsed) return false;
keypath.push_back(parsed->ChildNumber());
first = false;
}
return true;
}
std::string FormatHDKeypath(const std::vector<uint32_t>& path, bool apostrophe)
{
std::string ret;
for (auto i : path) {
ret += strprintf("/%i", (i << 1) >> 1);
if (i >> 31) ret += apostrophe ? '\'' : 'h';
}
return ret;
}
std::string WriteHDKeypath(const std::vector<uint32_t>& keypath, bool apostrophe)
{
return "m" + FormatHDKeypath(keypath, apostrophe);
}
bool HasHardenedDerivation(std::span<const uint32_t> keypath)
{
return std::any_of(keypath.begin(), keypath.end(), [](uint32_t index) {
return index >> 31;
});
}