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) 2014-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 <key_io.h>7#include <base58.h>8#include <bech32.h>9#include <script/interpreter.h>10#include <script/solver.h>11#include <tinyformat.h>12#include <util/overflow.h>13#include <util/strencodings.h>15#include <algorithm>16#include <cassert>17#include <cstring>19/// Maximum witness length for Bech32 addresses.20static constexpr std::size_t BECH32_WITNESS_PROG_MAX_LEN = 40;22namespace {23class DestinationEncoder24{25private:26const CChainParams& m_params;28public:29explicit DestinationEncoder(const CChainParams& params) : m_params(params) {}31std::string operator()(const PKHash& id) const32{33std::vector<unsigned char> data = m_params.Base58Prefix(CChainParams::PUBKEY_ADDRESS);34data.insert(data.end(), id.begin(), id.end());35return EncodeBase58Check(data);36}38std::string operator()(const ScriptHash& id) const39{40std::vector<unsigned char> data = m_params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);41data.insert(data.end(), id.begin(), id.end());42return EncodeBase58Check(data);43}45std::string operator()(const WitnessV0KeyHash& id) const46{47std::vector<unsigned char> data = {0};48data.reserve(33);49ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, id.begin(), id.end());50return bech32::Encode(bech32::Encoding::BECH32, m_params.Bech32HRP(), data);51}53std::string operator()(const WitnessV0ScriptHash& id) const54{55std::vector<unsigned char> data = {0};56data.reserve(53);57ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, id.begin(), id.end());58return bech32::Encode(bech32::Encoding::BECH32, m_params.Bech32HRP(), data);59}61std::string operator()(const WitnessV1Taproot& tap) const62{63std::vector<unsigned char> data = {1};64data.reserve(53);65ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, tap.begin(), tap.end());66return bech32::Encode(bech32::Encoding::BECH32M, m_params.Bech32HRP(), data);67}69std::string operator()(const WitnessUnknown& id) const70{71const std::vector<unsigned char>& program = id.GetWitnessProgram();72if (id.GetWitnessVersion() < 1 || id.GetWitnessVersion() > 16 || program.size() < 2 || program.size() > 40) {73return {};74}75std::vector<unsigned char> data = {(unsigned char)id.GetWitnessVersion()};76data.reserve(1 + CeilDiv(program.size() * 8, 5u));77ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, program.begin(), program.end());78return bech32::Encode(bech32::Encoding::BECH32M, m_params.Bech32HRP(), data);79}81std::string operator()(const CNoDestination& no) const { return {}; }82std::string operator()(const PubKeyDestination& pk) const { return {}; }83};85CTxDestination DecodeDestination(const std::string& str, const CChainParams& params, std::string& error_str, std::vector<int>* error_locations)86{87std::vector<unsigned char> data;88uint160 hash;89error_str = "";91// Note this will be false if it is a valid Bech32 address for a different network92bool is_bech32 = (ToLower(str.substr(0, params.Bech32HRP().size())) == params.Bech32HRP());94if (!is_bech32 && DecodeBase58Check(str, data, 21)) {95// base58-encoded Bitcoin addresses.96// Public-key-hash-addresses have version 0 (or 111 testnet).97// The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key.98const std::vector<unsigned char>& pubkey_prefix = params.Base58Prefix(CChainParams::PUBKEY_ADDRESS);99if (data.size() == hash.size() + pubkey_prefix.size() && std::equal(pubkey_prefix.begin(), pubkey_prefix.end(), data.begin())) {100std::copy(data.begin() + pubkey_prefix.size(), data.end(), hash.begin());101return PKHash(hash);102}103// Script-hash-addresses have version 5 (or 196 testnet).104// The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script.105const std::vector<unsigned char>& script_prefix = params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);106if (data.size() == hash.size() + script_prefix.size() && std::equal(script_prefix.begin(), script_prefix.end(), data.begin())) {107std::copy(data.begin() + script_prefix.size(), data.end(), hash.begin());108return ScriptHash(hash);109}111// If the prefix of data matches either the script or pubkey prefix, the length must have been wrong112if ((data.size() >= script_prefix.size() &&113std::equal(script_prefix.begin(), script_prefix.end(), data.begin())) ||114(data.size() >= pubkey_prefix.size() &&115std::equal(pubkey_prefix.begin(), pubkey_prefix.end(), data.begin()))) {116error_str = "Invalid length for Base58 address (P2PKH or P2SH)";117} else {118error_str = "Invalid or unsupported Base58-encoded address.";119}120return CNoDestination();121} else if (!is_bech32) {122// Try Base58 decoding without the checksum, using a much larger max length123if (!DecodeBase58(str, data, 100)) {124error_str = "Invalid or unsupported Segwit (Bech32) or Base58 encoding.";125} else {126error_str = "Invalid checksum or length of Base58 address (P2PKH or P2SH)";127}128return CNoDestination();129}131data.clear();132const auto dec = bech32::Decode(str);133if (dec.encoding == bech32::Encoding::BECH32 || dec.encoding == bech32::Encoding::BECH32M) {134if (dec.data.empty()) {135error_str = "Empty Bech32 data section";136return CNoDestination();137}138// Bech32 decoding139if (dec.hrp != params.Bech32HRP()) {140error_str = strprintf("Invalid or unsupported prefix for Segwit (Bech32) address (expected %s, got %s).", params.Bech32HRP(), dec.hrp);141return CNoDestination();142}143int version = dec.data[0]; // The first 5 bit symbol is the witness version (0-16)144if (version == 0 && dec.encoding != bech32::Encoding::BECH32) {145error_str = "Version 0 witness address must use Bech32 checksum";146return CNoDestination();147}148if (version != 0 && dec.encoding != bech32::Encoding::BECH32M) {149error_str = "Version 1+ witness address must use Bech32m checksum";150return CNoDestination();151}152// The rest of the symbols are converted witness program bytes.153data.reserve(((dec.data.size() - 1) * 5) / 8);154if (ConvertBits<5, 8, false>([&](unsigned char c) { data.push_back(c); }, dec.data.begin() + 1, dec.data.end())) {156std::string_view byte_str{data.size() == 1 ? "byte" : "bytes"};158if (version == 0) {159{160WitnessV0KeyHash keyid;161if (data.size() == keyid.size()) {162std::copy(data.begin(), data.end(), keyid.begin());163return keyid;164}165}166{167WitnessV0ScriptHash scriptid;168if (data.size() == scriptid.size()) {169std::copy(data.begin(), data.end(), scriptid.begin());170return scriptid;171}172}174error_str = strprintf("Invalid Bech32 v0 address program size (%d %s), per BIP141", data.size(), byte_str);175return CNoDestination();176}178if (version == 1 && data.size() == WITNESS_V1_TAPROOT_SIZE) {179static_assert(WITNESS_V1_TAPROOT_SIZE == WitnessV1Taproot::size());180WitnessV1Taproot tap;181std::copy(data.begin(), data.end(), tap.begin());182return tap;183}185if (CScript::IsPayToAnchor(version, data)) {186return PayToAnchor();187}189if (version > 16) {190error_str = "Invalid Bech32 address witness version";191return CNoDestination();192}194if (data.size() < 2 || data.size() > BECH32_WITNESS_PROG_MAX_LEN) {195error_str = strprintf("Invalid Bech32 address program size (%d %s)", data.size(), byte_str);196return CNoDestination();197}199return WitnessUnknown{version, data};200} else {201error_str = strprintf("Invalid padding in Bech32 data section");202return CNoDestination();203}204}206// Perform Bech32 error location207auto res = bech32::LocateErrors(str);208error_str = res.first;209if (error_locations) *error_locations = std::move(res.second);210return CNoDestination();211}212} // namespace214CKey DecodeSecret(const std::string& str)215{216CKey key;217std::vector<unsigned char> data;218if (DecodeBase58Check(str, data, 34)) {219const std::vector<unsigned char>& privkey_prefix = Params().Base58Prefix(CChainParams::SECRET_KEY);220if ((data.size() == 32 + privkey_prefix.size() || (data.size() == 33 + privkey_prefix.size() && data.back() == 1)) &&221std::equal(privkey_prefix.begin(), privkey_prefix.end(), data.begin())) {222bool compressed = data.size() == 33 + privkey_prefix.size();223key.Set(data.begin() + privkey_prefix.size(), data.begin() + privkey_prefix.size() + 32, compressed);224}225}226if (!data.empty()) {227memory_cleanse(data.data(), data.size());228}229return key;230}232std::string EncodeSecret(const CKey& key)233{234assert(key.IsValid());235std::vector<unsigned char> data = Params().Base58Prefix(CChainParams::SECRET_KEY);236data.insert(data.end(), UCharCast(key.begin()), UCharCast(key.end()));237if (key.IsCompressed()) {238data.push_back(1);239}240std::string ret = EncodeBase58Check(data);241memory_cleanse(data.data(), data.size());242return ret;243}245CExtPubKey DecodeExtPubKey(const std::string& str)246{247CExtPubKey key;248std::vector<unsigned char> data;249if (DecodeBase58Check(str, data, 78)) {250const std::vector<unsigned char>& prefix = Params().Base58Prefix(CChainParams::EXT_PUBLIC_KEY);