Bitcoin Core 32.99.0
P2P Digital Currency
key_io.cpp
Go to the documentation of this file.
1// Copyright (c) 2014-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 <key_io.h>
6
7#include <base58.h>
8#include <bech32.h>
10#include <script/solver.h>
11#include <streams.h>
12#include <tinyformat.h>
13#include <util/overflow.h>
14#include <util/strencodings.h>
15
16#include <algorithm>
17#include <cassert>
18#include <cstring>
19
21static constexpr std::size_t BECH32_WITNESS_PROG_MAX_LEN = 40;
22
23namespace {
24class DestinationEncoder
25{
26private:
27 const CChainParams& m_params;
28
29public:
30 explicit DestinationEncoder(const CChainParams& params) : m_params(params) {}
31
32 std::string operator()(const PKHash& id) const
33 {
34 std::vector<unsigned char> data = m_params.Base58Prefix(CChainParams::PUBKEY_ADDRESS);
35 data.insert(data.end(), id.begin(), id.end());
36 return EncodeBase58Check(data);
37 }
38
39 std::string operator()(const ScriptHash& id) const
40 {
41 std::vector<unsigned char> data = m_params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);
42 data.insert(data.end(), id.begin(), id.end());
43 return EncodeBase58Check(data);
44 }
45
46 std::string operator()(const WitnessV0KeyHash& id) const
47 {
48 std::vector<unsigned char> data = {0};
49 data.reserve(33);
50 ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, id.begin(), id.end());
52 }
53
54 std::string operator()(const WitnessV0ScriptHash& id) const
55 {
56 std::vector<unsigned char> data = {0};
57 data.reserve(53);
58 ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, id.begin(), id.end());
60 }
61
62 std::string operator()(const WitnessV1Taproot& tap) const
63 {
64 std::vector<unsigned char> data = {1};
65 data.reserve(53);
66 ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, tap.begin(), tap.end());
68 }
69
70 std::string operator()(const WitnessUnknown& id) const
71 {
72 const std::vector<unsigned char>& program = id.GetWitnessProgram();
73 if (id.GetWitnessVersion() < 1 || id.GetWitnessVersion() > 16 || program.size() < 2 || program.size() > 40) {
74 return {};
75 }
76 std::vector<unsigned char> data = {(unsigned char)id.GetWitnessVersion()};
77 data.reserve(1 + CeilDiv(program.size() * 8, 5u));
78 ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, program.begin(), program.end());
80 }
81
82 std::string operator()(const CNoDestination& no) const { return {}; }
83 std::string operator()(const PubKeyDestination& pk) const { return {}; }
84};
85
86CTxDestination DecodeDestination(const std::string& str, const CChainParams& params, std::string& error_str, std::vector<int>* error_locations)
87{
88 std::vector<unsigned char> data;
89 uint160 hash;
90 error_str = "";
91
92 // Note this will be false if it is a valid Bech32 address for a different network
93 bool is_bech32 = (ToLower(str.substr(0, params.Bech32HRP().size())) == params.Bech32HRP());
94
95 if (!is_bech32 && DecodeBase58Check(str, data, 21)) {
96 // base58-encoded Bitcoin addresses.
97 // Public-key-hash-addresses have version 0 (or 111 testnet).
98 // The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key.
99 const std::vector<unsigned char>& pubkey_prefix = params.Base58Prefix(CChainParams::PUBKEY_ADDRESS);
100 if (data.size() == hash.size() + pubkey_prefix.size() && std::equal(pubkey_prefix.begin(), pubkey_prefix.end(), data.begin())) {
101 std::copy(data.begin() + pubkey_prefix.size(), data.end(), hash.begin());
102 return PKHash(hash);
103 }
104 // Script-hash-addresses have version 5 (or 196 testnet).
105 // The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script.
106 const std::vector<unsigned char>& script_prefix = params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);
107 if (data.size() == hash.size() + script_prefix.size() && std::equal(script_prefix.begin(), script_prefix.end(), data.begin())) {
108 std::copy(data.begin() + script_prefix.size(), data.end(), hash.begin());
109 return ScriptHash(hash);
110 }
111
112 // If the prefix of data matches either the script or pubkey prefix, the length must have been wrong
113 if ((data.size() >= script_prefix.size() &&
114 std::equal(script_prefix.begin(), script_prefix.end(), data.begin())) ||
115 (data.size() >= pubkey_prefix.size() &&
116 std::equal(pubkey_prefix.begin(), pubkey_prefix.end(), data.begin()))) {
117 error_str = "Invalid length for Base58 address (P2PKH or P2SH)";
118 } else {
119 error_str = "Invalid or unsupported Base58-encoded address.";
120 }
121 return CNoDestination();
122 } else if (!is_bech32) {
123 // Try Base58 decoding without the checksum, using a much larger max length
124 if (!DecodeBase58(str, data, 100)) {
125 error_str = "Invalid or unsupported Segwit (Bech32) or Base58 encoding.";
126 } else {
127 error_str = "Invalid checksum or length of Base58 address (P2PKH or P2SH)";
128 }
129 return CNoDestination();
130 }
131
132 data.clear();
133 const auto dec = bech32::Decode(str);
134 if (dec.encoding == bech32::Encoding::BECH32 || dec.encoding == bech32::Encoding::BECH32M) {
135 if (dec.data.empty()) {
136 error_str = "Empty Bech32 data section";
137 return CNoDestination();
138 }
139 // Bech32 decoding
140 if (dec.hrp != params.Bech32HRP()) {
141 error_str = strprintf("Invalid or unsupported prefix for Segwit (Bech32) address (expected %s, got %s).", params.Bech32HRP(), dec.hrp);
142 return CNoDestination();
143 }
144 int version = dec.data[0]; // The first 5 bit symbol is the witness version (0-16)
145 if (version == 0 && dec.encoding != bech32::Encoding::BECH32) {
146 error_str = "Version 0 witness address must use Bech32 checksum";
147 return CNoDestination();
148 }
149 if (version != 0 && dec.encoding != bech32::Encoding::BECH32M) {
150 error_str = "Version 1+ witness address must use Bech32m checksum";
151 return CNoDestination();
152 }
153 // The rest of the symbols are converted witness program bytes.
154 data.reserve(((dec.data.size() - 1) * 5) / 8);
155 if (ConvertBits<5, 8, false>([&](unsigned char c) { data.push_back(c); }, dec.data.begin() + 1, dec.data.end())) {
156
157 std::string_view byte_str{data.size() == 1 ? "byte" : "bytes"};
158
159 if (version == 0) {
160 {
161 WitnessV0KeyHash keyid;
162 if (data.size() == keyid.size()) {
163 std::copy(data.begin(), data.end(), keyid.begin());
164 return keyid;
165 }
166 }
167 {
168 WitnessV0ScriptHash scriptid;
169 if (data.size() == scriptid.size()) {
170 std::copy(data.begin(), data.end(), scriptid.begin());
171 return scriptid;
172 }
173 }
174
175 error_str = strprintf("Invalid Bech32 v0 address program size (%d %s), per BIP141", data.size(), byte_str);
176 return CNoDestination();
177 }
178
179 if (version == 1 && data.size() == WITNESS_V1_TAPROOT_SIZE) {
182 std::copy(data.begin(), data.end(), tap.begin());
183 return tap;
184 }
185
186 if (CScript::IsPayToAnchor(version, data)) {
187 return PayToAnchor();
188 }
189
190 if (version > 16) {
191 error_str = "Invalid Bech32 address witness version";
192 return CNoDestination();
193 }
194
195 if (data.size() < 2 || data.size() > BECH32_WITNESS_PROG_MAX_LEN) {
196 error_str = strprintf("Invalid Bech32 address program size (%d %s)", data.size(), byte_str);
197 return CNoDestination();
198 }
199
200 return WitnessUnknown{version, data};
201 } else {
202 error_str = strprintf("Invalid padding in Bech32 data section");
203 return CNoDestination();
204 }
205 }
206
207 // Perform Bech32 error location
208 auto res = bech32::LocateErrors(str);
209 error_str = res.first;
210 if (error_locations) *error_locations = std::move(res.second);
211 return CNoDestination();
212}
213} // namespace
214
215CKey DecodeSecret(const std::string& str)
216{
217 CKey key;
218 std::vector<unsigned char> data;
219 if (DecodeBase58Check(str, data, 34)) {
220 const std::vector<unsigned char>& privkey_prefix = Params().Base58Prefix(CChainParams::SECRET_KEY);
221 if ((data.size() == 32 + privkey_prefix.size() || (data.size() == 33 + privkey_prefix.size() && data.back() == 1)) &&
222 std::equal(privkey_prefix.begin(), privkey_prefix.end(), data.begin())) {
223 bool compressed = data.size() == 33 + privkey_prefix.size();
224 key.Set(data.begin() + privkey_prefix.size(), data.begin() + privkey_prefix.size() + 32, compressed);
225 }
226 }
227 if (!data.empty()) {
228 memory_cleanse(data.data(), data.size());
229 }
230 return key;
231}
232
233std::string EncodeSecret(const CKey& key)
234{
235 assert(key.IsValid());
236 std::vector<unsigned char> data = Params().Base58Prefix(CChainParams::SECRET_KEY);
237 data.insert(data.end(), UCharCast(key.begin()), UCharCast(key.end()));
238 if (key.IsCompressed()) {
239 data.push_back(1);
240 }
241 std::string ret = EncodeBase58Check(data);
242 memory_cleanse(data.data(), data.size());
243 return ret;
244}
245
246CExtPubKey DecodeExtPubKey(const std::string& str)
247{
248 CExtPubKey key;
249 std::vector<unsigned char> data;
250 if (DecodeBase58Check(str, data, 78)) {
251 const std::vector<unsigned char>& prefix = Params().Base58Prefix(CChainParams::EXT_PUBLIC_KEY);
252 if (data.size() == BIP32_EXTKEY_SIZE + prefix.size() && std::equal(prefix.begin(), prefix.end(), data.begin())) {
253 SpanReader{std::span{data}.subspan(prefix.size())} >> key;
254 }
255 }
256 return key;
257}
258
259std::string EncodeExtPubKey(const CExtPubKey& key)
260{
261 std::vector<unsigned char> data = Params().Base58Prefix(CChainParams::EXT_PUBLIC_KEY);
262 VectorWriter{data, data.size(), key};
263 std::string ret = EncodeBase58Check(data);
264 return ret;
265}
266
267CExtKey DecodeExtKey(const std::string& str)
268{
269 CExtKey key;
270 std::vector<unsigned char> data;
271 if (DecodeBase58Check(str, data, 78)) {
272 const std::vector<unsigned char>& prefix = Params().Base58Prefix(CChainParams::EXT_SECRET_KEY);
273 if (data.size() == BIP32_EXTKEY_SIZE + prefix.size() && std::equal(prefix.begin(), prefix.end(), data.begin())) {
274 SpanReader{std::span{data}.subspan(prefix.size())} >> key;
275 }
276 }
277 if (!data.empty()) {
278 memory_cleanse(data.data(), data.size());
279 }
280 return key;
281}
282
283std::string EncodeExtKey(const CExtKey& key)
284{
285 std::vector<unsigned char> data = Params().Base58Prefix(CChainParams::EXT_SECRET_KEY);
286 VectorWriter{data, data.size(), key};
287 std::string ret = EncodeBase58Check(data);
288 memory_cleanse(data.data(), data.size());
289 return ret;
290}
291
292std::string EncodeDestination(const CTxDestination& dest)
293{
294 return std::visit(DestinationEncoder(Params()), dest);
295}
296
297CTxDestination DecodeDestination(const std::string& str, std::string& error_msg, std::vector<int>* error_locations)
298{
299 return DecodeDestination(str, Params(), error_msg, error_locations);
300}
301
302CTxDestination DecodeDestination(const std::string& str)
303{
304 std::string error_msg;
305 return DecodeDestination(str, error_msg);
306}
307
308bool IsValidDestinationString(const std::string& str, const CChainParams& params)
309{
310 std::string error_msg;
311 return IsValidDestination(DecodeDestination(str, params, error_msg, nullptr));
312}
313
314bool IsValidDestinationString(const std::string& str)
315{
316 return IsValidDestinationString(str, Params());
317}
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination corresponds to one with an address.
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, PayToAnchor, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
Definition: addresstype.h:143
static bool DecodeBase58Check(const char *psz, std::vector< unsigned char > &vchRet, int max_ret_len)
Definition: base58.cpp:146
static bool DecodeBase58(const char *psz, std::vector< unsigned char > &vch, int max_ret_len)
Definition: base58.cpp:40
std::string EncodeBase58Check(std::span< const unsigned char > input)
Encode a byte span into a base58-encoded string, including checksum.
Definition: base58.cpp:137
int ret
const CChainParams & Params()
Return the currently selected parameters.
size_t size() const
Definition: hash_type.h:58
unsigned char * begin()
Definition: hash_type.h:18
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:77
const std::vector< unsigned char > & Base58Prefix(Base58Type type) const
Definition: chainparams.h:114
const std::string & Bech32HRP() const
Definition: chainparams.h:115
An encapsulated private key.
Definition: key.h:46
bool IsValid() const
Check whether this private key is valid.
Definition: key.h:134
const std::byte * begin() const
Definition: key.h:130
bool IsCompressed() const
Check whether the public key corresponding to this private key is (to be) compressed.
Definition: key.h:137
const std::byte * end() const
Definition: key.h:131
void Set(const T pbegin, const T pend, bool fCompressedIn)
Initialize using begin and end iterators to byte data.
Definition: key.h:114
bool IsPayToAnchor() const
Definition: script.cpp:207
Minimal stream for reading from an existing byte array by std::span.
Definition: streams.h:83
const unsigned char * end() const
Definition: pubkey.h:305
const unsigned char * begin() const
Definition: pubkey.h:304
static constexpr size_t size()
Definition: pubkey.h:302
static constexpr unsigned int size()
Definition: uint256.h:107
constexpr unsigned char * begin()
Definition: uint256.h:101
160-bit opaque blob.
Definition: uint256.h:184
void memory_cleanse(void *ptr, size_t len)
Secure overwrite a buffer (possibly containing secret data) with zero-bytes.
Definition: cleanse.cpp:14
static const PrecomputedData data
Precomputed COutPoint and CCoins values.
constexpr size_t WITNESS_V1_TAPROOT_SIZE
Definition: interpreter.h:240
static constexpr std::size_t BECH32_WITNESS_PROG_MAX_LEN
Maximum witness length for Bech32 addresses.
Definition: key_io.cpp:21
bool IsValidDestinationString(const std::string &str, const CChainParams &params)
Definition: key_io.cpp:308
std::string EncodeExtKey(const CExtKey &key)
Definition: key_io.cpp:283
CExtPubKey DecodeExtPubKey(const std::string &str)
Definition: key_io.cpp:246
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg, std::vector< int > *error_locations)
Definition: key_io.cpp:297
std::string EncodeSecret(const CKey &key)
Definition: key_io.cpp:233
std::string EncodeDestination(const CTxDestination &dest)
Definition: key_io.cpp:292
CKey DecodeSecret(const std::string &str)
Definition: key_io.cpp:215
std::string EncodeExtPubKey(const CExtPubKey &key)
Definition: key_io.cpp:259
CExtKey DecodeExtKey(const std::string &str)
Definition: key_io.cpp:267
std::pair< std::string, std::vector< int > > LocateErrors(const std::string &str, CharLimit limit)
Find index of an incorrect character in a Bech32 string.
Definition: bech32.cpp:402
@ BECH32
Bech32 encoding as defined in BIP173.
@ BECH32M
Bech32m encoding as defined in BIP350.
DecodeResult Decode(const std::string &str, CharLimit limit)
Decode a Bech32 or Bech32m string.
Definition: bech32.cpp:373
std::string Encode(Encoding encoding, const std::string &hrp, const data &values)
Encode a Bech32 or Bech32m string.
Definition: bech32.cpp:357
constexpr auto CeilDiv(const Dividend dividend, const Divisor divisor)
Integer ceiling division (for unsigned values).
Definition: overflow.h:70
constexpr unsigned int BIP32_EXTKEY_SIZE
Definition: pubkey.h:22
const char * prefix
Definition: rest.cpp:1197
unsigned char * UCharCast(char *c)
Definition: span.h:95
Definition: key.h:238
CTxDestination subtype to encode any future Witness version.
Definition: addresstype.h:96
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
std::string ToLower(std::string_view str)
Returns the lowercase equivalent of the given string.
assert(!tx.IsCoinBase())