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) 2015-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 <common/url.h>7#include <charconv>8#include <cstddef>9#include <string>10#include <string_view>11#include <system_error>13std::string UrlDecode(std::string_view url_encoded)14{15std::string res;16res.reserve(url_encoded.size());18for (size_t i = 0; i < url_encoded.size(); ++i) {19char c = url_encoded[i];20// Special handling for percent which should be followed by two hex digits21// representing an octet values, see RFC 3986, Section 2.1 Percent-Encoding22if (c == '%' && i + 2 < url_encoded.size()) {23unsigned int decoded_value{0};24auto [p, ec] = std::from_chars(url_encoded.data() + i + 1, url_encoded.data() + i + 3, decoded_value, 16);26// Only if there is no error and the pointer is set to the end of27// the string, we can be sure both characters were valid hex28if (ec == std::errc{} && p == url_encoded.data() + i + 3) {29res += static_cast<char>(decoded_value);30// Next two characters are part of the percent encoding31i += 2;32continue;33}34// In case of invalid percent encoding, add the '%' and continue35}36res += c;37}39return res;40}42std::string UrlEncode(std::string_view str)43{44std::string res;45res.reserve(str.size() * 3); // worst case: every char needs encoding47for (char ch : str) {48auto c = static_cast<unsigned char>(ch);49// Unreserved characters per RFC 3986, Section 2.350if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||51(c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' || c == '~') {52res += ch;53} else {54// Percent-encode all other characters55res += '%';56constexpr char hex_chars[] = "0123456789ABCDEF";57res += hex_chars[(c >> 4) & 0xF];58res += hex_chars[c & 0xF];59}60}61return res;62}