Bitcoin Core  22.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";
111  } else {
112  error_str = "Invalid prefix for 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 = "Not a valid Bech32 or Base58 encoding";
119  } else {
120  error_str = "Invalid checksum or length of Base58 address";
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) && dec.data.size() > 0) {
128  // Bech32 decoding
129  if (dec.hrp != params.Bech32HRP()) {
130  error_str = "Invalid prefix for Bech32 address";
131  return CNoDestination();
132  }
133  int version = dec.data[0]; // The first 5 bit symbol is the witness version (0-16)
134  if (version == 0 && dec.encoding != bech32::Encoding::BECH32) {
135  error_str = "Version 0 witness address must use Bech32 checksum";
136  return CNoDestination();
137  }
138  if (version != 0 && dec.encoding != bech32::Encoding::BECH32M) {
139  error_str = "Version 1+ witness address must use Bech32m checksum";
140  return CNoDestination();
141  }
142  // The rest of the symbols are converted witness program bytes.
143  data.reserve(((dec.data.size() - 1) * 5) / 8);
144  if (ConvertBits<5, 8, false>([&](unsigned char c) { data.push_back(c); }, dec.data.begin() + 1, dec.data.end())) {
145  if (version == 0) {
146  {
147  WitnessV0KeyHash keyid;
148  if (data.size() == keyid.size()) {
149  std::copy(data.begin(), data.end(), keyid.begin());
150  return keyid;
151  }
152  }
153  {
154  WitnessV0ScriptHash scriptid;
155  if (data.size() == scriptid.size()) {
156  std::copy(data.begin(), data.end(), scriptid.begin());
157  return scriptid;
158  }
159  }
160 
161  error_str = "Invalid Bech32 v0 address data size";
162  return CNoDestination();
163  }
164 
165  if (version == 1 && data.size() == WITNESS_V1_TAPROOT_SIZE) {
167  WitnessV1Taproot tap;
168  std::copy(data.begin(), data.end(), tap.begin());
169  return tap;
170  }
171 
172  if (version > 16) {
173  error_str = "Invalid Bech32 address witness version";
174  return CNoDestination();
175  }
176 
177  if (data.size() < 2 || data.size() > BECH32_WITNESS_PROG_MAX_LEN) {
178  error_str = "Invalid Bech32 address data size";
179  return CNoDestination();
180  }
181 
182  WitnessUnknown unk;
183  unk.version = version;
184  std::copy(data.begin(), data.end(), unk.program);
185  unk.length = data.size();
186  return unk;
187  }
188  }
189 
190  // Perform Bech32 error location
191  auto res = bech32::LocateErrors(str);
192  error_str = res.first;
193  if (error_locations) *error_locations = std::move(res.second);
194  return CNoDestination();
195 }
196 } // namespace
197 
198 CKey DecodeSecret(const std::string& str)
199 {
200  CKey key;
201  std::vector<unsigned char> data;
202  if (DecodeBase58Check(str, data, 34)) {
203  const std::vector<unsigned char>& privkey_prefix = Params().Base58Prefix(CChainParams::SECRET_KEY);
204  if ((data.size() == 32 + privkey_prefix.size() || (data.size() == 33 + privkey_prefix.size() && data.back() == 1)) &&
205  std::equal(privkey_prefix.begin(), privkey_prefix.end(), data.begin())) {
206  bool compressed = data.size() == 33 + privkey_prefix.size();
207  key.Set(data.begin() + privkey_prefix.size(), data.begin() + privkey_prefix.size() + 32, compressed);
208  }
209  }
210  if (!data.empty()) {
211  memory_cleanse(data.data(), data.size());
212  }
213  return key;
214 }
215 
216 std::string EncodeSecret(const CKey& key)
217 {
218  assert(key.IsValid());
219  std::vector<unsigned char> data = Params().Base58Prefix(CChainParams::SECRET_KEY);
220  data.insert(data.end(), key.begin(), key.end());
221  if (key.IsCompressed()) {
222  data.push_back(1);
223  }
224  std::string ret = EncodeBase58Check(data);
225  memory_cleanse(data.data(), data.size());
226  return ret;
227 }
228 
229 CExtPubKey DecodeExtPubKey(const std::string& str)
230 {
231  CExtPubKey key;
232  std::vector<unsigned char> data;
233  if (DecodeBase58Check(str, data, 78)) {
234  const std::vector<unsigned char>& prefix = Params().Base58Prefix(CChainParams::EXT_PUBLIC_KEY);
235  if (data.size() == BIP32_EXTKEY_SIZE + prefix.size() && std::equal(prefix.begin(), prefix.end(), data.begin())) {
236  key.Decode(data.data() + prefix.size());
237  }
238  }
239  return key;
240 }
241 
242 std::string EncodeExtPubKey(const CExtPubKey& key)
243 {
244  std::vector<unsigned char> data = Params().Base58Prefix(CChainParams::EXT_PUBLIC_KEY);
245  size_t size = data.size();
246  data.resize(size + BIP32_EXTKEY_SIZE);
247  key.Encode(data.data() + size);
248  std::string ret = EncodeBase58Check(data);
249  return ret;
250 }
251 
252 CExtKey DecodeExtKey(const std::string& str)
253 {
254  CExtKey key;
255  std::vector<unsigned char> data;
256  if (DecodeBase58Check(str, data, 78)) {
257  const std::vector<unsigned char>& prefix = Params().Base58Prefix(CChainParams::EXT_SECRET_KEY);
258  if (data.size() == BIP32_EXTKEY_SIZE + prefix.size() && std::equal(prefix.begin(), prefix.end(), data.begin())) {
259  key.Decode(data.data() + prefix.size());
260  }
261  }
262  return key;
263 }
264 
265 std::string EncodeExtKey(const CExtKey& key)
266 {
267  std::vector<unsigned char> data = Params().Base58Prefix(CChainParams::EXT_SECRET_KEY);
268  size_t size = data.size();
269  data.resize(size + BIP32_EXTKEY_SIZE);
270  key.Encode(data.data() + size);
271  std::string ret = EncodeBase58Check(data);
272  memory_cleanse(data.data(), data.size());
273  return ret;
274 }
275 
276 std::string EncodeDestination(const CTxDestination& dest)
277 {
278  return std::visit(DestinationEncoder(Params()), dest);
279 }
280 
281 CTxDestination DecodeDestination(const std::string& str, std::string& error_msg, std::vector<int>* error_locations)
282 {
283  return DecodeDestination(str, Params(), error_msg, error_locations);
284 }
285 
286 CTxDestination DecodeDestination(const std::string& str)
287 {
288  std::string error_msg;
289  return DecodeDestination(str, error_msg);
290 }
291 
292 bool IsValidDestinationString(const std::string& str, const CChainParams& params)
293 {
294  std::string error_msg;
295  return IsValidDestination(DecodeDestination(str, params, error_msg, nullptr));
296 }
297 
298 bool IsValidDestinationString(const std::string& str)
299 {
300  return IsValidDestinationString(str, Params());
301 }
CKey::IsCompressed
bool IsCompressed() const
Check whether the public key corresponding to this private key is (to be) compressed.
Definition: key.h:96
BIP32_EXTKEY_SIZE
const unsigned int BIP32_EXTKEY_SIZE
Definition: pubkey.h:19
DecodeBase58Check
static bool DecodeBase58Check(const char *psz, std::vector< unsigned char > &vchRet, int max_ret_len)
Definition: base58.cpp:144
CChainParams::EXT_PUBLIC_KEY
@ EXT_PUBLIC_KEY
Definition: chainparams.h:76
WitnessUnknown
CTxDestination subtype to encode any future Witness version.
Definition: standard.h:125
assert
assert(!tx.IsCoinBase())
key_io.h
bech32::Decode
DecodeResult Decode(const std::string &str)
Decode a Bech32 or Bech32m string.
Definition: bech32.cpp:372
WitnessUnknown::version
unsigned int version
Definition: standard.h:127
string.h
CKey::Set
void Set(const T pbegin, const T pend, bool fCompressedIn)
Initialize using begin and end iterators to byte data.
Definition: key.h:73
base_blob::size
static constexpr unsigned int size()
Definition: uint256.h:80
BaseHash::begin
unsigned char * begin()
Definition: hash_type.h:18
CChainParams
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:69
WitnessUnknown::length
unsigned int length
Definition: standard.h:128
CExtKey::Encode
void Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const
Definition: key.cpp:365
memory_cleanse
void memory_cleanse(void *ptr, size_t len)
Secure overwrite a buffer (possibly containing secret data) with zero-bytes.
Definition: cleanse.cpp:14
CExtPubKey::Decode
void Decode(const unsigned char code[BIP32_EXTKEY_SIZE])
Definition: pubkey.cpp:346
CKey::end
const unsigned char * end() const
Definition: key.h:90
bech32::Encoding::BECH32
@ BECH32
Bech32 encoding as defined in BIP173.
WitnessV0KeyHash
Definition: standard.h:109
prefix
const char * prefix
Definition: rest.cpp:926
EncodeBase58Check
std::string EncodeBase58Check(Span< const unsigned char > input)
Encode a byte span into a base58-encoded string, including checksum.
Definition: base58.cpp:135
XOnlyPubKey::begin
const unsigned char * begin() const
Definition: pubkey.h:282
CKey::begin
const unsigned char * begin() const
Definition: key.h:89
strencodings.h
CTxDestination
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:157
IsValidDestination
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:332
EncodeSecret
std::string EncodeSecret(const CKey &key)
Definition: key_io.cpp:216
CExtKey
Definition: key.h:161
CChainParams::SECRET_KEY
@ SECRET_KEY
Definition: chainparams.h:75
EncodeExtKey
std::string EncodeExtKey(const CExtKey &key)
Definition: key_io.cpp:265
XOnlyPubKey::end
const unsigned char * end() const
Definition: pubkey.h:283
CChainParams::Base58Prefix
const std::vector< unsigned char > & Base58Prefix(Base58Type type) const
Definition: chainparams.h:115
CKey::IsValid
bool IsValid() const
Check whether this private key is valid.
Definition: key.h:93
DecodeSecret
CKey DecodeSecret(const std::string &str)
Definition: key_io.cpp:198
CExtPubKey::Encode
void Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const
Definition: pubkey.cpp:337
bech32::LocateErrors
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:399
CNoDestination
Definition: standard.h:73
DecodeBase58
static bool DecodeBase58(const char *psz, std::vector< unsigned char > &vch, int max_ret_len)
Definition: base58.cpp:38
DecodeExtPubKey
CExtPubKey DecodeExtPubKey(const std::string &str)
Definition: key_io.cpp:229
PKHash
Definition: standard.h:79
DecodeExtKey
CExtKey DecodeExtKey(const std::string &str)
Definition: key_io.cpp:252
uint160
160-bit opaque blob.
Definition: uint256.h:115
CChainParams::EXT_SECRET_KEY
@ EXT_SECRET_KEY
Definition: chainparams.h:77
bech32::Encoding::BECH32M
@ BECH32M
Bech32m encoding as defined in BIP350.
CKey
An encapsulated private key.
Definition: key.h:26
BaseHash::size
size_t size() const
Definition: hash_type.h:63
CExtKey::Decode
void Decode(const unsigned char code[BIP32_EXTKEY_SIZE])
Definition: key.cpp:375
DecodeDestination
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg, std::vector< int > *error_locations)
Definition: key_io.cpp:281
Params
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:561
BECH32_WITNESS_PROG_MAX_LEN
static constexpr std::size_t BECH32_WITNESS_PROG_MAX_LEN
Maximum witness length for Bech32 addresses.
Definition: key_io.cpp:16
CChainParams::PUBKEY_ADDRESS
@ PUBKEY_ADDRESS
Definition: chainparams.h:73
IsValidDestinationString
bool IsValidDestinationString(const std::string &str, const CChainParams &params)
Definition: key_io.cpp:292
bech32.h
WITNESS_V1_TAPROOT_SIZE
static constexpr size_t WITNESS_V1_TAPROOT_SIZE
Definition: interpreter.h:227
base58.h
EncodeExtPubKey
std::string EncodeExtPubKey(const CExtPubKey &key)
Definition: key_io.cpp:242
XOnlyPubKey::size
static constexpr size_t size()
Definition: pubkey.h:281
CChainParams::Bech32HRP
const std::string & Bech32HRP() const
Definition: chainparams.h:116
WitnessV0ScriptHash
Definition: standard.h:102
bech32::Encode
std::string Encode(Encoding encoding, const std::string &hrp, const data &values)
Encode a Bech32 or Bech32m string.
Definition: bech32.cpp:356
CExtPubKey
Definition: pubkey.h:291
CChainParams::SCRIPT_ADDRESS
@ SCRIPT_ADDRESS
Definition: chainparams.h:74
ScriptHash
Definition: standard.h:89
base_blob::begin
unsigned char * begin()
Definition: uint256.h:60
EncodeDestination
std::string EncodeDestination(const CTxDestination &dest)
Definition: key_io.cpp:276
WitnessUnknown::program
unsigned char program[40]
Definition: standard.h:129
ToLower
std::string ToLower(const std::string &str)
Returns the lowercase equivalent of the given string.
Definition: strencodings.cpp:490
WitnessV1Taproot
Definition: standard.h:118