1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin Developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
8 // Why base-58 instead of standard base-64 encoding?
9 // - Don't want 0OIl characters that look the same in some fonts and
10 // could be used to create visually identical looking account numbers.
11 // - A string with non-alphanumeric characters is not as easily accepted as an account number.
12 // - E-mail usually won't line-break if there's no punctuation to break at.
13 // - Double-clicking selects the whole number as one word if it's all alphanumeric.
15 #ifndef BITCOIN_BASE58_H
16 #define BITCOIN_BASE58_H
20 #include <openssl/crypto.h> // for OPENSSL_cleanse()
25 static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
27 // Encode a byte sequence as a base58-encoded string
28 inline std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
34 // Convert big endian data to little endian
35 // Extra zero at the end make sure bignum will interpret as a positive number
36 std::vector<unsigned char> vchTmp(pend-pbegin+1, 0);
37 reverse_copy(pbegin, pend, vchTmp.begin());
39 // Convert little endian data to bignum
43 // Convert bignum to std::string
45 // Expected size increase from base58 conversion is approximately 137%
46 // use 138% to be safe
47 str.reserve((pend - pbegin) * 138 / 100 + 1);
52 if (!BN_div(&dv, &rem, &bn, &bn58, pctx))
53 throw bignum_error("EncodeBase58 : BN_div failed");
55 unsigned int c = rem.getuint32();
59 // Leading zeroes encoded as base58 zeros
60 for (const unsigned char* p = pbegin; p < pend && *p == 0; p++)
63 // Convert little endian std::string to big endian
64 reverse(str.begin(), str.end());
68 // Encode a byte vector as a base58-encoded string
69 inline std::string EncodeBase58(const std::vector<unsigned char>& vch)
71 return EncodeBase58(&vch[0], &vch[0] + vch.size());
74 // Decode a base58-encoded string psz into byte vector vchRet
75 // returns true if decoding is successful
76 inline bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet)
86 // Convert big endian string to bignum
87 for (const char* p = psz; *p; p++)
89 const char* p1 = strchr(pszBase58, *p);
98 bnChar.setuint32((uint32_t)(p1 - pszBase58));
99 if (!BN_mul(&bn, &bn, &bn58, pctx))
100 throw bignum_error("DecodeBase58 : BN_mul failed");
104 // Get bignum as little endian data
105 std::vector<unsigned char> vchTmp = bn.getvch();
107 // Trim off sign byte if present
108 if (vchTmp.size() >= 2 && vchTmp.end()[-1] == 0 && vchTmp.end()[-2] >= 0x80)
109 vchTmp.erase(vchTmp.end()-1);
111 // Restore leading zeros
112 int nLeadingZeros = 0;
113 for (const char* p = psz; *p == pszBase58[0]; p++)
115 vchRet.assign(nLeadingZeros + vchTmp.size(), 0);
117 // Convert little endian data to big endian
118 reverse_copy(vchTmp.begin(), vchTmp.end(), vchRet.end() - vchTmp.size());
122 // Decode a base58-encoded string str into byte vector vchRet
123 // returns true if decoding is successful
124 inline bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
126 return DecodeBase58(str.c_str(), vchRet);
132 // Encode a byte vector to a base58-encoded string, including checksum
133 inline std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
135 // add 4-byte hash check to the end
136 std::vector<unsigned char> vch(vchIn);
137 uint256 hash = Hash(vch.begin(), vch.end());
138 vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
139 return EncodeBase58(vch);
142 // Decode a base58-encoded string psz that includes a checksum, into byte vector vchRet
143 // returns true if decoding is successful
144 inline bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
146 if (!DecodeBase58(psz, vchRet))
148 if (vchRet.size() < 4)
153 uint256 hash = Hash(vchRet.begin(), vchRet.end()-4);
154 if (memcmp(&hash, &vchRet.end()[-4], 4) != 0)
159 vchRet.resize(vchRet.size()-4);
163 // Decode a base58-encoded string str that includes a checksum, into byte vector vchRet
164 // returns true if decoding is successful
165 inline bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
167 return DecodeBase58Check(str.c_str(), vchRet);
174 /** Base class for all base58-encoded data */
179 unsigned char nVersion;
181 // the actually encoded data
182 std::vector<unsigned char> vchData;
192 // zero the memory, as it may contain sensitive data
193 if (!vchData.empty())
194 OPENSSL_cleanse(&vchData[0], vchData.size());
197 void SetData(int nVersionIn, const void* pdata, size_t nSize)
199 nVersion = nVersionIn;
200 vchData.resize(nSize);
201 if (!vchData.empty())
202 memcpy(&vchData[0], pdata, nSize);
205 void SetData(int nVersionIn, const unsigned char *pbegin, const unsigned char *pend)
207 SetData(nVersionIn, (void*)pbegin, pend - pbegin);
211 bool SetString(const char* psz)
213 std::vector<unsigned char> vchTemp;
214 DecodeBase58Check(psz, vchTemp);
221 nVersion = vchTemp[0];
222 vchData.resize(vchTemp.size() - 1);
223 if (!vchData.empty())
224 memcpy(&vchData[0], &vchTemp[1], vchData.size());
225 OPENSSL_cleanse(&vchTemp[0], vchData.size());
229 bool SetString(const std::string& str)
231 return SetString(str.c_str());
234 std::string ToString() const
236 std::vector<unsigned char> vch(1, nVersion);
237 vch.insert(vch.end(), vchData.begin(), vchData.end());
238 return EncodeBase58Check(vch);
241 int CompareTo(const CBase58Data& b58) const
243 if (nVersion < b58.nVersion) return -1;
244 if (nVersion > b58.nVersion) return 1;
245 if (vchData < b58.vchData) return -1;
246 if (vchData > b58.vchData) return 1;
250 bool operator==(const CBase58Data& b58) const { return CompareTo(b58) == 0; }
251 bool operator<=(const CBase58Data& b58) const { return CompareTo(b58) <= 0; }
252 bool operator>=(const CBase58Data& b58) const { return CompareTo(b58) >= 0; }
253 bool operator< (const CBase58Data& b58) const { return CompareTo(b58) < 0; }
254 bool operator> (const CBase58Data& b58) const { return CompareTo(b58) > 0; }
257 /** base58-encoded Bitcoin addresses.
258 * Public-key-hash-addresses have version 0 (or 111 testnet).
259 * The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key.
260 * Script-hash-addresses have version 5 (or 196 testnet).
261 * The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script.
263 class CBitcoinAddress;
264 class CBitcoinAddressVisitor : public boost::static_visitor<bool>
267 CBitcoinAddress *addr;
269 CBitcoinAddressVisitor(CBitcoinAddress *addrIn) : addr(addrIn) { }
270 bool operator()(const CKeyID &id) const;
271 bool operator()(const CScriptID &id) const;
272 bool operator()(const CNoDestination &no) const;
275 class CBitcoinAddress : public CBase58Data
282 PUBKEY_ADDRESS_TEST = 111,
283 SCRIPT_ADDRESS_TEST = 196,
286 bool Set(const CKeyID &id) {
287 SetData(fTestNet ? PUBKEY_ADDRESS_TEST : PUBKEY_ADDRESS, &id, 20);
291 bool Set(const CScriptID &id) {
292 SetData(fTestNet ? SCRIPT_ADDRESS_TEST : SCRIPT_ADDRESS, &id, 20);
296 bool Set(const CTxDestination &dest)
298 return boost::apply_visitor(CBitcoinAddressVisitor(this), dest);
303 unsigned int nExpectedSize = 20;
304 bool fExpectTestNet = false;
308 nExpectedSize = 20; // Hash of public key
309 fExpectTestNet = false;
312 nExpectedSize = 20; // Hash of CScript
313 fExpectTestNet = false;
316 case PUBKEY_ADDRESS_TEST:
318 fExpectTestNet = true;
320 case SCRIPT_ADDRESS_TEST:
322 fExpectTestNet = true;
328 return fExpectTestNet == fTestNet && vchData.size() == nExpectedSize;
335 CBitcoinAddress(const CTxDestination &dest)
340 CBitcoinAddress(const std::string& strAddress)
342 SetString(strAddress);
345 CBitcoinAddress(const char* pszAddress)
347 SetString(pszAddress);
350 CTxDestination Get() const {
352 return CNoDestination();
355 case PUBKEY_ADDRESS_TEST: {
357 memcpy(&id, &vchData[0], 20);
361 case SCRIPT_ADDRESS_TEST: {
363 memcpy(&id, &vchData[0], 20);
364 return CScriptID(id);
367 return CNoDestination();
370 bool GetKeyID(CKeyID &keyID) const {
375 case PUBKEY_ADDRESS_TEST: {
377 memcpy(&id, &vchData[0], 20);
381 default: return false;
385 bool IsScript() const {
390 case SCRIPT_ADDRESS_TEST: {
393 default: return false;
398 bool inline CBitcoinAddressVisitor::operator()(const CKeyID &id) const { return addr->Set(id); }
399 bool inline CBitcoinAddressVisitor::operator()(const CScriptID &id) const { return addr->Set(id); }
400 bool inline CBitcoinAddressVisitor::operator()(const CNoDestination &id) const { return false; }
402 /** A base58-encoded secret key */
403 class CBitcoinSecret : public CBase58Data
406 void SetSecret(const CSecret& vchSecret, bool fCompressed)
408 assert(vchSecret.size() == 32);
409 SetData(128 + (fTestNet ? CBitcoinAddress::PUBKEY_ADDRESS_TEST : CBitcoinAddress::PUBKEY_ADDRESS), &vchSecret[0], vchSecret.size());
411 vchData.push_back(1);
414 CSecret GetSecret(bool &fCompressedOut)
417 vchSecret.resize(32);
418 memcpy(&vchSecret[0], &vchData[0], 32);
419 fCompressedOut = vchData.size() == 33;
425 bool fExpectTestNet = false;
428 case (128 + CBitcoinAddress::PUBKEY_ADDRESS):
431 case (128 + CBitcoinAddress::PUBKEY_ADDRESS_TEST):
432 fExpectTestNet = true;
438 return fExpectTestNet == fTestNet && (vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1));
441 bool SetString(const char* pszSecret)
443 return CBase58Data::SetString(pszSecret) && IsValid();
446 bool SetString(const std::string& strSecret)
448 return SetString(strSecret.c_str());
451 CBitcoinSecret(const CSecret& vchSecret, bool fCompressed)
453 SetSecret(vchSecret, fCompressed);