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 9.2KB

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