You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

base58.cpp 8.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. // Copyright (c) 2014-2015 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. #include "base58.h"
  5. #include "hash.h"
  6. #include "uint256.h"
  7. #include <assert.h>
  8. #include <stdint.h>
  9. #include <string.h>
  10. #include <vector>
  11. #include <string>
  12. #include <boost/variant/apply_visitor.hpp>
  13. #include <boost/variant/static_visitor.hpp>
  14. /** All alphanumeric characters except for "0", "I", "O", and "l" */
  15. static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
  16. bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch)
  17. {
  18. // Skip leading spaces.
  19. while (*psz && isspace(*psz))
  20. psz++;
  21. // Skip and count leading '1's.
  22. int zeroes = 0;
  23. while (*psz == '1') {
  24. zeroes++;
  25. psz++;
  26. }
  27. // Allocate enough space in big-endian base256 representation.
  28. std::vector<unsigned char> b256(strlen(psz) * 733 / 1000 + 1); // log(58) / log(256), rounded up.
  29. // Process the characters.
  30. while (*psz && !isspace(*psz)) {
  31. // Decode base58 character
  32. const char* ch = strchr(pszBase58, *psz);
  33. if (ch == NULL)
  34. return false;
  35. // Apply "b256 = b256 * 58 + ch".
  36. int carry = ch - pszBase58;
  37. for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); it != b256.rend(); it++) {
  38. carry += 58 * (*it);
  39. *it = carry % 256;
  40. carry /= 256;
  41. }
  42. assert(carry == 0);
  43. psz++;
  44. }
  45. // Skip trailing spaces.
  46. while (isspace(*psz))
  47. psz++;
  48. if (*psz != 0)
  49. return false;
  50. // Skip leading zeroes in b256.
  51. std::vector<unsigned char>::iterator it = b256.begin();
  52. while (it != b256.end() && *it == 0)
  53. it++;
  54. // Copy result into output vector.
  55. vch.reserve(zeroes + (b256.end() - it));
  56. vch.assign(zeroes, 0x00);
  57. while (it != b256.end())
  58. vch.push_back(*(it++));
  59. return true;
  60. }
  61. std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
  62. {
  63. // Skip & count leading zeroes.
  64. int zeroes = 0;
  65. while (pbegin != pend && *pbegin == 0) {
  66. pbegin++;
  67. zeroes++;
  68. }
  69. // Allocate enough space in big-endian base58 representation.
  70. std::vector<unsigned char> b58((pend - pbegin) * 138 / 100 + 1); // log(256) / log(58), rounded up.
  71. // Process the bytes.
  72. while (pbegin != pend) {
  73. int carry = *pbegin;
  74. // Apply "b58 = b58 * 256 + ch".
  75. for (std::vector<unsigned char>::reverse_iterator it = b58.rbegin(); it != b58.rend(); it++) {
  76. carry += 256 * (*it);
  77. *it = carry % 58;
  78. carry /= 58;
  79. }
  80. assert(carry == 0);
  81. pbegin++;
  82. }
  83. // Skip leading zeroes in base58 result.
  84. std::vector<unsigned char>::iterator it = b58.begin();
  85. while (it != b58.end() && *it == 0)
  86. it++;
  87. // Translate the result into a string.
  88. std::string str;
  89. str.reserve(zeroes + (b58.end() - it));
  90. str.assign(zeroes, '1');
  91. while (it != b58.end())
  92. str += pszBase58[*(it++)];
  93. return str;
  94. }
  95. std::string EncodeBase58(const std::vector<unsigned char>& vch)
  96. {
  97. return EncodeBase58(&vch[0], &vch[0] + vch.size());
  98. }
  99. bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
  100. {
  101. return DecodeBase58(str.c_str(), vchRet);
  102. }
  103. std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
  104. {
  105. // add 4-byte hash check to the end
  106. std::vector<unsigned char> vch(vchIn);
  107. uint256 hash = Hash(vch.begin(), vch.end());
  108. vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
  109. return EncodeBase58(vch);
  110. }
  111. bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
  112. {
  113. if (!DecodeBase58(psz, vchRet) ||
  114. (vchRet.size() < 4)) {
  115. vchRet.clear();
  116. return false;
  117. }
  118. // re-calculate the checksum, insure it matches the included 4-byte checksum
  119. uint256 hash = Hash(vchRet.begin(), vchRet.end() - 4);
  120. if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) {
  121. vchRet.clear();
  122. return false;
  123. }
  124. vchRet.resize(vchRet.size() - 4);
  125. return true;
  126. }
  127. bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
  128. {
  129. return DecodeBase58Check(str.c_str(), vchRet);
  130. }
  131. CBase58Data::CBase58Data()
  132. {
  133. vchVersion.clear();
  134. vchData.clear();
  135. }
  136. void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const void* pdata, size_t nSize)
  137. {
  138. vchVersion = vchVersionIn;
  139. vchData.resize(nSize);
  140. if (!vchData.empty())
  141. memcpy(&vchData[0], pdata, nSize);
  142. }
  143. void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const unsigned char* pbegin, const unsigned char* pend)
  144. {
  145. SetData(vchVersionIn, (void*)pbegin, pend - pbegin);
  146. }
  147. bool CBase58Data::SetString(const char* psz, unsigned int nVersionBytes)
  148. {
  149. std::vector<unsigned char> vchTemp;
  150. bool rc58 = DecodeBase58Check(psz, vchTemp);
  151. if ((!rc58) || (vchTemp.size() < nVersionBytes)) {
  152. vchData.clear();
  153. vchVersion.clear();
  154. return false;
  155. }
  156. vchVersion.assign(vchTemp.begin(), vchTemp.begin() + nVersionBytes);
  157. vchData.resize(vchTemp.size() - nVersionBytes);
  158. if (!vchData.empty())
  159. memcpy(&vchData[0], &vchTemp[nVersionBytes], vchData.size());
  160. memory_cleanse(&vchTemp[0], vchData.size());
  161. return true;
  162. }
  163. bool CBase58Data::SetString(const std::string& str)
  164. {
  165. return SetString(str.c_str());
  166. }
  167. std::string CBase58Data::ToString() const
  168. {
  169. std::vector<unsigned char> vch = vchVersion;
  170. vch.insert(vch.end(), vchData.begin(), vchData.end());
  171. return EncodeBase58Check(vch);
  172. }
  173. int CBase58Data::CompareTo(const CBase58Data& b58) const
  174. {
  175. if (vchVersion < b58.vchVersion)
  176. return -1;
  177. if (vchVersion > b58.vchVersion)
  178. return 1;
  179. if (vchData < b58.vchData)
  180. return -1;
  181. if (vchData > b58.vchData)
  182. return 1;
  183. return 0;
  184. }
  185. namespace
  186. {
  187. class CBitcoinAddressVisitor : public boost::static_visitor<bool>
  188. {
  189. private:
  190. CBitcoinAddress* addr;
  191. public:
  192. CBitcoinAddressVisitor(CBitcoinAddress* addrIn) : addr(addrIn) {}
  193. bool operator()(const CKeyID& id) const { return addr->Set(id); }
  194. bool operator()(const CScriptID& id) const { return addr->Set(id); }
  195. bool operator()(const CNoDestination& no) const { return false; }
  196. };
  197. } // anon namespace
  198. bool CBitcoinAddress::Set(const CKeyID& id)
  199. {
  200. SetData(Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS), &id, 20);
  201. return true;
  202. }
  203. bool CBitcoinAddress::Set(const CScriptID& id)
  204. {
  205. SetData(Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS), &id, 20);
  206. return true;
  207. }
  208. bool CBitcoinAddress::Set(const CTxDestination& dest)
  209. {
  210. return boost::apply_visitor(CBitcoinAddressVisitor(this), dest);
  211. }
  212. bool CBitcoinAddress::IsValid() const
  213. {
  214. return IsValid(Params());
  215. }
  216. bool CBitcoinAddress::IsValid(const CChainParams& params) const
  217. {
  218. bool fCorrectSize = vchData.size() == 20;
  219. bool fKnownVersion = vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS) ||
  220. vchVersion == params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);
  221. return fCorrectSize && fKnownVersion;
  222. }
  223. CTxDestination CBitcoinAddress::Get() const
  224. {
  225. if (!IsValid())
  226. return CNoDestination();
  227. uint160 id;
  228. memcpy(&id, &vchData[0], 20);
  229. if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
  230. return CKeyID(id);
  231. else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS))
  232. return CScriptID(id);
  233. else
  234. return CNoDestination();
  235. }
  236. bool CBitcoinAddress::GetKeyID(CKeyID& keyID) const
  237. {
  238. if (!IsValid() || vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
  239. return false;
  240. uint160 id;
  241. memcpy(&id, &vchData[0], 20);
  242. keyID = CKeyID(id);
  243. return true;
  244. }
  245. bool CBitcoinAddress::IsScript() const
  246. {
  247. return IsValid() && vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS);
  248. }
  249. void CBitcoinSecret::SetKey(const CKey& vchSecret)
  250. {
  251. assert(vchSecret.IsValid());
  252. SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size());
  253. if (vchSecret.IsCompressed())
  254. vchData.push_back(1);
  255. }
  256. CKey CBitcoinSecret::GetKey()
  257. {
  258. CKey ret;
  259. assert(vchData.size() >= 32);
  260. ret.Set(vchData.begin(), vchData.begin() + 32, vchData.size() > 32 && vchData[32] == 1);
  261. return ret;
  262. }
  263. bool CBitcoinSecret::IsValid() const
  264. {
  265. bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1);
  266. bool fCorrectVersion = vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY);
  267. return fExpectedFormat && fCorrectVersion;
  268. }
  269. bool CBitcoinSecret::SetString(const char* pszSecret)
  270. {
  271. return CBase58Data::SetString(pszSecret) && IsValid();
  272. }
  273. bool CBitcoinSecret::SetString(const std::string& strSecret)
  274. {
  275. return SetString(strSecret.c_str());
  276. }