Inside Bitcoin
Opening the selected file…
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) 2019-present The Bitcoin Core developers2// Distributed under the MIT software license, see the accompanying3// file COPYING or http://www.opensource.org/licenses/mit-license.php.5#include <util/bip32.h>7#include <tinyformat.h>8#include <util/strencodings.h>10#include <algorithm>11#include <cstdint>12#include <optional>13#include <span>14#include <sstream>15#include <string_view>17util::Expected<KeyPathElement, std::string> ParseKeyPathElement(std::span<const char> elem)18{19const std::string_view raw{elem.begin(), elem.end()};20if (elem.empty()) {21return util::Unexpected{strprintf("Key path value '%s' is not valid", raw)};22}24bool is_hardened = false;25const char last = elem.back();26if (last == '\'' || last == 'h') {27elem = elem.first(elem.size() - 1);28is_hardened = true;29}31const auto number{ToIntegral<uint32_t>(std::string_view{elem.begin(), elem.end()})};32if (!number) {33return util::Unexpected{strprintf("Key path value '%s' is not a valid uint32", raw)};34}35if (*number >= BIP32_HARDENED_FLAG) {36return util::Unexpected{strprintf("Key path value %u is out of range", *number)};37}38return KeyPathElement{*number, is_hardened};39}41bool ParseHDKeypath(const std::string& keypath_str, std::vector<uint32_t>& keypath)42{43std::stringstream ss(keypath_str);44std::string item;45bool first = true;46while (std::getline(ss, item, '/') || std::getline(ss, item, 'h')) {47if (item.compare("m") == 0) {48if (first) {49first = false;50continue;51}52return false;53}54const auto parsed{ParseKeyPathElement(std::span<const char>{item.data(), item.size()})};55if (!parsed) return false;56keypath.push_back(parsed->ChildNumber());57first = false;58}59return true;60}62std::string FormatHDKeypath(const std::vector<uint32_t>& path, bool apostrophe)63{64std::string ret;65for (auto i : path) {66ret += strprintf("/%i", (i << 1) >> 1);67if (i >> 31) ret += apostrophe ? '\'' : 'h';68}69return ret;70}72std::string WriteHDKeypath(const std::vector<uint32_t>& keypath, bool apostrophe)73{74return "m" + FormatHDKeypath(keypath, apostrophe);75}77bool HasHardenedDerivation(std::span<const uint32_t> keypath)78{79return std::any_of(keypath.begin(), keypath.end(), [](uint32_t index) {80return index >> 31;81});82}
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.