Coverage Report

Created: 2026-08-14 20:23

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/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
94
{
17
94
    std::stringstream ss(keypath_str);
18
94
    std::string item;
19
94
    bool first = true;
20
453
    while (std::getline(ss, item, '/')) {
21
382
        if (item.compare("m") == 0) {
22
68
            if (first) {
23
68
                first = false;
24
68
                continue;
25
68
            }
26
0
            return false;
27
68
        }
28
        // Finds whether it is hardened
29
314
        uint32_t path = 0;
30
314
        size_t pos = item.find('\'');
31
314
        if (pos != std::string::npos) {
32
            // The hardened tick can only be in the last index of the string
33
157
            if (pos != item.size() - 1) {
34
3
                return false;
35
3
            }
36
154
            path |= 0x80000000;
37
154
            item = item.substr(0, item.size() - 1); // Drop the last character which is the hardened tick
38
154
        }
39
40
        // Ensure this is only numbers
41
311
        const auto number{ToIntegral<uint32_t>(item)};
42
311
        if (!number) {
43
20
            return false;
44
20
        }
45
291
        path |= *number;
46
47
291
        keypath.push_back(path);
48
291
        first = false;
49
291
    }
50
71
    return true;
51
94
}
52
53
std::string FormatHDKeypath(const std::vector<uint32_t>& path, bool apostrophe)
54
212k
{
55
212k
    std::string ret;
56
638k
    for (auto i : path) {
57
638k
        ret += strprintf("/%i", (i << 1) >> 1);
58
638k
        if (i >> 31) ret += apostrophe ? '\'' : 'h';
59
638k
    }
60
212k
    return ret;
61
212k
}
62
63
std::string WriteHDKeypath(const std::vector<uint32_t>& keypath, bool apostrophe)
64
2.87k
{
65
2.87k
    return "m" + FormatHDKeypath(keypath, apostrophe);
66
2.87k
}