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.
18 #include <openssl/crypto.h> // for OPENSSL_cleanse()
24 static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
26 // Encode a byte sequence as a base58-encoded string
27 std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
33 // Convert big endian data to little endian
34 // Extra zero at the end make sure bignum will interpret as a positive number
35 std::vector<unsigned char> vchTmp(pend-pbegin+1, 0);
36 reverse_copy(pbegin, pend, vchTmp.begin());
38 // Convert little endian data to bignum
42 // Convert bignum to std::string
44 // Expected size increase from base58 conversion is approximately 137%
45 // use 138% to be safe
46 str.reserve((pend - pbegin) * 138 / 100 + 1);
51 if (!BN_div(dv.get(), rem.get(), bn.get(), bn58.get(), pctx))
52 throw bignum_error("EncodeBase58 : BN_div failed");
54 unsigned int c = rem.getuint32();
58 // Leading zeroes encoded as base58 zeros
59 for (const unsigned char* p = pbegin; p < pend && *p == 0; p++)
62 // Convert little endian std::string to big endian
63 reverse(str.begin(), str.end());
67 // Encode a byte vector as a base58-encoded string
68 std::string EncodeBase58(const std::vector<unsigned char>& vch)
70 return EncodeBase58(&vch[0], &vch[0] + vch.size());
73 // Decode a base58-encoded string psz into byte vector vchRet
74 // returns true if decoding is successful
75 bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet)
85 // Convert big endian string to bignum
86 for (const char* p = psz; *p; p++)
88 const char* p1 = strchr(pszBase58, *p);
97 bnChar.setuint32((uint32_t)(p1 - pszBase58));
98 if (!BN_mul(bn.get(), bn.get(), bn58.get(), pctx))
99 throw bignum_error("DecodeBase58 : BN_mul failed");
103 // Get bignum as little endian data
104 std::vector<unsigned char> vchTmp = bn.getvch();
106 // Trim off sign byte if present
107 if (vchTmp.size() >= 2 && vchTmp.end()[-1] == 0 && vchTmp.end()[-2] >= 0x80)
108 vchTmp.erase(vchTmp.end()-1);
110 // Restore leading zeros
111 int nLeadingZeros = 0;
112 for (const char* p = psz; *p == pszBase58[0]; p++)
114 vchRet.assign(nLeadingZeros + vchTmp.size(), 0);
116 // Convert little endian data to big endian
117 reverse_copy(vchTmp.begin(), vchTmp.end(), vchRet.end() - vchTmp.size());
121 // Decode a base58-encoded string str into byte vector vchRet
122 // returns true if decoding is successful
123 bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
125 return DecodeBase58(str.c_str(), vchRet);
128 // Encode a byte vector to a base58-encoded string, including checksum
129 std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
131 // add 4-byte hash check to the end
132 std::vector<unsigned char> vch(vchIn);
133 uint256 hash = Hash(vch.begin(), vch.end());
134 vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
135 return EncodeBase58(vch);
138 // Decode a base58-encoded string psz that includes a checksum, into byte vector vchRet
139 // returns true if decoding is successful
140 bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
142 if (!DecodeBase58(psz, vchRet))
144 if (vchRet.size() < 4)
149 uint256 hash = Hash(vchRet.begin(), vchRet.end()-4);
150 if (memcmp(&hash, &vchRet.end()[-4], 4) != 0)
155 vchRet.resize(vchRet.size()-4);
159 // Decode a base58-encoded string str that includes a checksum, into byte vector vchRet
160 // returns true if decoding is successful
161 bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
163 return DecodeBase58Check(str.c_str(), vchRet);
166 CBase58Data::CBase58Data()
172 CBase58Data::~CBase58Data()
174 // zero the memory, as it may contain sensitive data
175 if (!vchData.empty())
176 OPENSSL_cleanse(&vchData[0], vchData.size());
179 void CBase58Data::SetData(int nVersionIn, const void* pdata, size_t nSize)
181 nVersion = nVersionIn;
182 vchData.resize(nSize);
183 if (!vchData.empty())
184 memcpy(&vchData[0], pdata, nSize);
187 const std::vector<unsigned char> &CBase58Data::GetData() const
192 void CBase58Data::SetData(int nVersionIn, const unsigned char *pbegin, const unsigned char *pend)
194 SetData(nVersionIn, (void*)pbegin, pend - pbegin);
197 bool CBase58Data::SetString(const char* psz)
199 std::vector<unsigned char> vchTemp;
200 DecodeBase58Check(psz, vchTemp);
207 nVersion = vchTemp[0];
208 vchData.resize(vchTemp.size() - 1);
209 if (!vchData.empty())
210 memcpy(&vchData[0], &vchTemp[1], vchData.size());
211 OPENSSL_cleanse(&vchTemp[0], vchData.size());
215 bool CBase58Data::SetString(const std::string& str)
217 return SetString(str.c_str());
220 std::string CBase58Data::ToString() const
222 std::vector<unsigned char> vch(1, nVersion);
223 vch.insert(vch.end(), vchData.begin(), vchData.end());
224 return EncodeBase58Check(vch);
227 int CBase58Data::CompareTo(const CBase58Data& b58) const
229 if (nVersion < b58.nVersion) return -1;
230 if (nVersion > b58.nVersion) return 1;
231 if (vchData < b58.vchData) return -1;
232 if (vchData > b58.vchData) return 1;
236 bool CBitcoinAddress::Set(const CKeyID &id) {
237 SetData(fTestNet ? PUBKEY_ADDRESS_TEST : PUBKEY_ADDRESS, &id, 20);
241 bool CBitcoinAddress::Set(const CScriptID &id) {
242 SetData(fTestNet ? SCRIPT_ADDRESS_TEST : SCRIPT_ADDRESS, &id, 20);
246 bool CBitcoinAddress::Set(const CTxDestination &dest)
248 return boost::apply_visitor(CBitcoinAddressVisitor(this), dest);
251 bool CBitcoinAddress::Set(const CMalleablePubKey &mpk) {
252 std::vector<unsigned char> vchPubkeyPair = mpk.Raw();
253 SetData(fTestNet ? PUBKEY_PAIR_ADDRESS_TEST : PUBKEY_PAIR_ADDRESS, &vchPubkeyPair[0], 68);
257 bool CBitcoinAddress::Set(const CBitcoinAddress &dest)
259 nVersion = dest.nVersion;
260 vchData = dest.vchData;
264 bool CBitcoinAddress::IsValid() const
266 unsigned int nExpectedSize = 20;
267 bool fExpectTestNet = false;
271 case PUBKEY_PAIR_ADDRESS:
272 nExpectedSize = 68; // Serialized pair of public keys
273 fExpectTestNet = false;
277 nExpectedSize = 20; // Hash of public key
278 fExpectTestNet = false;
281 nExpectedSize = 20; // Hash of CScript
282 fExpectTestNet = false;
285 case PUBKEY_PAIR_ADDRESS_TEST:
287 fExpectTestNet = true;
290 case PUBKEY_ADDRESS_TEST:
292 fExpectTestNet = true;
294 case SCRIPT_ADDRESS_TEST:
296 fExpectTestNet = true;
303 // Basic format sanity check
304 bool fSeemsSane = (fExpectTestNet == fTestNet && vchData.size() == nExpectedSize);
306 if (fSeemsSane && !fSimple)
308 // Perform dditional checking
309 // for pubkey pair addresses
310 CMalleablePubKey mpk;
312 return mpk.IsValid();
318 CTxDestination CBitcoinAddress::Get() const {
320 return CNoDestination();
323 case PUBKEY_ADDRESS_TEST: {
325 memcpy(&id, &vchData[0], 20);
329 case SCRIPT_ADDRESS_TEST: {
331 memcpy(&id, &vchData[0], 20);
332 return CScriptID(id);
335 return CNoDestination();
338 bool CBitcoinAddress::GetKeyID(CKeyID &keyID) const {
343 case PUBKEY_ADDRESS_TEST: {
345 memcpy(&id, &vchData[0], 20);
349 case PUBKEY_PAIR_ADDRESS:
350 case PUBKEY_PAIR_ADDRESS_TEST:
352 CMalleablePubKey mPubKey;
353 mPubKey.setvch(vchData);
354 keyID = mPubKey.GetID();
357 default: return false;
361 bool CBitcoinAddress::IsScript() const {
366 case SCRIPT_ADDRESS_TEST: {
369 default: return false;
373 bool CBitcoinAddress::IsPubKey() const {
378 case PUBKEY_ADDRESS_TEST: {
381 default: return false;
385 bool CBitcoinAddress::IsPair() const {
389 case PUBKEY_PAIR_ADDRESS:
390 case PUBKEY_PAIR_ADDRESS_TEST: {
393 default: return false;
397 void CBitcoinSecret::SetSecret(const CSecret& vchSecret, bool fCompressed)
399 assert(vchSecret.size() == 32);
400 SetData(128 + (fTestNet ? CBitcoinAddress::PUBKEY_ADDRESS_TEST : CBitcoinAddress::PUBKEY_ADDRESS), &vchSecret[0], vchSecret.size());
402 vchData.push_back(1);
405 CSecret CBitcoinSecret::GetSecret(bool &fCompressedOut)
408 vchSecret.resize(32);
409 memcpy(&vchSecret[0], &vchData[0], 32);
410 fCompressedOut = vchData.size() == 33;
414 bool CBitcoinSecret::IsValid() const
416 bool fExpectTestNet = false;
419 case (128 + CBitcoinAddress::PUBKEY_ADDRESS):
422 case (128 + CBitcoinAddress::PUBKEY_ADDRESS_TEST):
423 fExpectTestNet = true;
429 return fExpectTestNet == fTestNet && (vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1));
432 bool CBitcoinSecret::SetString(const char* pszSecret)
434 return CBase58Data::SetString(pszSecret) && IsValid();
437 bool CBitcoinSecret::SetString(const std::string& strSecret)
439 return SetString(strSecret.c_str());
442 CBitcoinSecret::CBitcoinSecret(const CSecret& vchSecret, bool fCompressed)
444 SetSecret(vchSecret, fCompressed);