Bitcoin Core  21.99.0
P2P Digital Currency
key_io.cpp
Go to the documentation of this file.
1 // Copyright (c) 2014-2019 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 WitnessUnknown& id) const
58  {
59  if (id.version < 1 || id.version > 16 || id.length < 2 || id.length > 40) {
60  return {};
61  }
62  std::vector<unsigned char> data = {(unsigned char)id.version};
63  data.reserve(1 + (id.length * 8 + 4) / 5);
64  ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, id.program, id.program + id.length);
65  return bech32::Encode(bech32::Encoding::BECH32M, m_params.Bech32HRP(), data);
66  }
67 
68  std::string operator()(const CNoDestination& no) const { return {}; }
69 };
70 
71 CTxDestination DecodeDestination(const std::string& str, const CChainParams& params, std::string& error_str)
72 {
73  std::vector<unsigned char> data;
74  uint160 hash;
75  error_str = "";
76  if (DecodeBase58Check(str, data, 21)) {
77  // base58-encoded Bitcoin addresses.
78  // Public-key-hash-addresses have version 0 (or 111 testnet).
79  // The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key.
80  const std::vector<unsigned char>& pubkey_prefix = params.Base58Prefix(CChainParams::PUBKEY_ADDRESS);
81  if (data.size() == hash.size() + pubkey_prefix.size() && std::equal(pubkey_prefix.begin(), pubkey_prefix.end(), data.begin())) {
82  std::copy(data.begin() + pubkey_prefix.size(), data.end(), hash.begin());
83  return PKHash(hash);
84  }
85  // Script-hash-addresses have version 5 (or 196 testnet).
86  // The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script.
87  const std::vector<unsigned char>& script_prefix = params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);
88  if (data.size() == hash.size() + script_prefix.size() && std::equal(script_prefix.begin(), script_prefix.end(), data.begin())) {
89  std::copy(data.begin() + script_prefix.size(), data.end(), hash.begin());
90  return ScriptHash(hash);
91  }
92 
93  // Set potential error message.
94  // This message may be changed if the address can also be interpreted as a Bech32 address.
95  error_str = "Invalid prefix for Base58-encoded address";
96  }
97  data.clear();
98  const auto dec = bech32::Decode(str);
99  if ((dec.encoding == bech32::Encoding::BECH32 || dec.encoding == bech32::Encoding::BECH32M) && dec.data.size() > 0) {
100  // Bech32 decoding
101  error_str = "";
102  if (dec.hrp != params.Bech32HRP()) {
103  error_str = "Invalid prefix for Bech32 address";
104  return CNoDestination();
105  }
106  int version = dec.data[0]; // The first 5 bit symbol is the witness version (0-16)
107  if (version == 0 && dec.encoding != bech32::Encoding::BECH32) {
108  error_str = "Version 0 witness address must use Bech32 checksum";
109  return CNoDestination();
110  }
111  if (version != 0 && dec.encoding != bech32::Encoding::BECH32M) {
112  error_str = "Version 1+ witness address must use Bech32m checksum";
113  return CNoDestination();
114  }
115  // The rest of the symbols are converted witness program bytes.
116  data.reserve(((dec.data.size() - 1) * 5) / 8);
117  if (ConvertBits<5, 8, false>([&](unsigned char c) { data.push_back(c); }, dec.data.begin() + 1, dec.data.end())) {
118  if (version == 0) {
119  {
120  WitnessV0KeyHash keyid;
121  if (data.size() == keyid.size()) {
122  std::copy(data.begin(), data.end(), keyid.begin());
123  return keyid;
124  }
125  }
126  {
127  WitnessV0ScriptHash scriptid;
128  if (data.size() == scriptid.size()) {
129  std::copy(data.begin(), data.end(), scriptid.begin());
130  return scriptid;
131  }
132  }
133 
134  error_str = "Invalid Bech32 v0 address data size";
135  return CNoDestination();
136  }
137 
138  if (version > 16) {
139  error_str = "Invalid Bech32 address witness version";
140  return CNoDestination();
141  }
142 
143  if (data.size() < 2 || data.size() > BECH32_WITNESS_PROG_MAX_LEN) {
144  error_str = "Invalid Bech32 address data size";
145  return CNoDestination();
146  }
147 
148  WitnessUnknown unk;
149  unk.version = version;
150  std::copy(data.begin(), data.end(), unk.program);
151  unk.length = data.size();
152  return unk;
153  }
154  }
155 
156  // Set error message if address can't be interpreted as Base58 or Bech32.
157  if (error_str.empty()) error_str = "Invalid address format";
158 
159  return CNoDestination();
160 }
161 } // namespace
162 
163 CKey DecodeSecret(const std::string& str)
164 {
165  CKey key;
166  std::vector<unsigned char> data;
167  if (DecodeBase58Check(str, data, 34)) {
168  const std::vector<unsigned char>& privkey_prefix = Params().Base58Prefix(CChainParams::SECRET_KEY);
169  if ((data.size() == 32 + privkey_prefix.size() || (data.size() == 33 + privkey_prefix.size() && data.back() == 1)) &&
170  std::equal(privkey_prefix.begin(), privkey_prefix.end(), data.begin())) {
171  bool compressed = data.size() == 33 + privkey_prefix.size();
172  key.Set(data.begin() + privkey_prefix.size(), data.begin() + privkey_prefix.size() + 32, compressed);
173  }
174  }
175  if (!data.empty()) {
176  memory_cleanse(data.data(), data.size());
177  }
178  return key;
179 }
180 
181 std::string EncodeSecret(const CKey& key)
182 {
183  assert(key.IsValid());
184  std::vector<unsigned char> data = Params().Base58Prefix(CChainParams::SECRET_KEY);
185  data.insert(data.end(), key.begin(), key.end());
186  if (key.IsCompressed()) {
187  data.push_back(1);
188  }
189  std::string ret = EncodeBase58Check(data);
190  memory_cleanse(data.data(), data.size());
191  return ret;
192 }
193 
194 CExtPubKey DecodeExtPubKey(const std::string& str)
195 {
196  CExtPubKey key;
197  std::vector<unsigned char> data;
198  if (DecodeBase58Check(str, data, 78)) {
199  const std::vector<unsigned char>& prefix = Params().Base58Prefix(CChainParams::EXT_PUBLIC_KEY);
200  if (data.size() == BIP32_EXTKEY_SIZE + prefix.size() && std::equal(prefix.begin(), prefix.end(), data.begin())) {
201  key.Decode(data.data() + prefix.size());
202  }
203  }
204  return key;
205 }
206 
207 std::string EncodeExtPubKey(const CExtPubKey& key)
208 {
209  std::vector<unsigned char> data = Params().Base58Prefix(CChainParams::EXT_PUBLIC_KEY);
210  size_t size = data.size();
211  data.resize(size + BIP32_EXTKEY_SIZE);
212  key.Encode(data.data() + size);
213  std::string ret = EncodeBase58Check(data);
214  return ret;
215 }
216 
217 CExtKey DecodeExtKey(const std::string& str)
218 {
219  CExtKey key;
220  std::vector<unsigned char> data;
221  if (DecodeBase58Check(str, data, 78)) {
222  const std::vector<unsigned char>& prefix = Params().Base58Prefix(CChainParams::EXT_SECRET_KEY);
223  if (data.size() == BIP32_EXTKEY_SIZE + prefix.size() && std::equal(prefix.begin(), prefix.end(), data.begin())) {
224  key.Decode(data.data() + prefix.size());
225  }
226  }
227  return key;
228 }
229 
230 std::string EncodeExtKey(const CExtKey& key)
231 {
232  std::vector<unsigned char> data = Params().Base58Prefix(CChainParams::EXT_SECRET_KEY);
233  size_t size = data.size();
234  data.resize(size + BIP32_EXTKEY_SIZE);
235  key.Encode(data.data() + size);
236  std::string ret = EncodeBase58Check(data);
237  memory_cleanse(data.data(), data.size());
238  return ret;
239 }
240 
241 std::string EncodeDestination(const CTxDestination& dest)
242 {
243  return std::visit(DestinationEncoder(Params()), dest);
244 }
245 
246 CTxDestination DecodeDestination(const std::string& str, std::string& error_msg)
247 {
248  return DecodeDestination(str, Params(), error_msg);
249 }
250 
251 CTxDestination DecodeDestination(const std::string& str)
252 {
253  std::string error_msg;
254  return DecodeDestination(str, error_msg);
255 }
256 
257 bool IsValidDestinationString(const std::string& str, const CChainParams& params)
258 {
259  std::string error_msg;
260  return IsValidDestination(DecodeDestination(str, params, error_msg));
261 }
262 
263 bool IsValidDestinationString(const std::string& str)
264 {
265  return IsValidDestinationString(str, Params());
266 }
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:18
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:71
WitnessUnknown
CTxDestination subtype to encode any future Witness version.
Definition: standard.h:180
key_io.h
bech32::Decode
DecodeResult Decode(const std::string &str)
Decode a Bech32 or Bech32m string.
Definition: bech32.cpp:168
WitnessUnknown::version
unsigned int version
Definition: standard.h:182
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:74
BaseHash::begin
unsigned char * begin()
Definition: standard.h:31
CChainParams
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:64
WitnessUnknown::length
unsigned int length
Definition: standard.h:183
CExtKey::Encode
void Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const
Definition: key.cpp:322
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:285
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:170
prefix
const char * prefix
Definition: rest.cpp:674
EncodeBase58Check
std::string EncodeBase58Check(Span< const unsigned char > input)
Encode a byte span into a base58-encoded string, including checksum.
Definition: base58.cpp:135
CKey::begin
const unsigned char * begin() const
Definition: key.h:89
strencodings.h
IsValidDestination
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:328
EncodeSecret
std::string EncodeSecret(const CKey &key)
Definition: key_io.cpp:181
CExtKey
Definition: key.h:144
CChainParams::SECRET_KEY
@ SECRET_KEY
Definition: chainparams.h:70
EncodeExtKey
std::string EncodeExtKey(const CExtKey &key)
Definition: key_io.cpp:230
CChainParams::Base58Prefix
const std::vector< unsigned char > & Base58Prefix(Base58Type type) const
Definition: chainparams.h:101
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:163
DecodeDestination
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg)
Definition: key_io.cpp:246
CExtPubKey::Encode
void Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const
Definition: pubkey.cpp:275
CNoDestination
Definition: standard.h:134
DecodeExtPubKey
CExtPubKey DecodeExtPubKey(const std::string &str)
Definition: key_io.cpp:194
PKHash
Definition: standard.h:140
DecodeExtKey
CExtKey DecodeExtKey(const std::string &str)
Definition: key_io.cpp:217
uint160
160-bit opaque blob.
Definition: uint256.h:113
CChainParams::EXT_SECRET_KEY
@ EXT_SECRET_KEY
Definition: chainparams.h:72
bech32::Encoding::BECH32M
@ BECH32M
Bech32m encoding as defined in BIP350.
CKey
An encapsulated private key.
Definition: key.h:27
BaseHash::size
size_t size() const
Definition: standard.h:76
CExtKey::Decode
void Decode(const unsigned char code[BIP32_EXTKEY_SIZE])
Definition: key.cpp:333
Params
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:523
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:68
CTxDestination
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:212
IsValidDestinationString
bool IsValidDestinationString(const std::string &str, const CChainParams &params)
Definition: key_io.cpp:257
bech32.h
base58.h
EncodeExtPubKey
std::string EncodeExtPubKey(const CExtPubKey &key)
Definition: key_io.cpp:207
CChainParams::Bech32HRP
const std::string & Bech32HRP() const
Definition: chainparams.h:102
WitnessV0ScriptHash
Definition: standard.h:163
bech32::Encode
std::string Encode(Encoding encoding, const std::string &hrp, const data &values)
Encode a Bech32 or Bech32m string.
Definition: bech32.cpp:152
assert
assert(std::addressof(::ChainstateActive().CoinsTip())==std::addressof(coins_cache))
base_blob::size
unsigned int size() const
Definition: uint256.h:78
CExtPubKey
Definition: pubkey.h:240
CChainParams::SCRIPT_ADDRESS
@ SCRIPT_ADDRESS
Definition: chainparams.h:69
ScriptHash
Definition: standard.h:150
base_blob::begin
unsigned char * begin()
Definition: uint256.h:58
EncodeDestination
std::string EncodeDestination(const CTxDestination &dest)
Definition: key_io.cpp:241
WitnessUnknown::program
unsigned char program[40]
Definition: standard.h:184