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