PageRenderTime 496ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/src/key.cpp

https://gitlab.com/Quetzalcoatl/VekitaCoin
C++ | 420 lines | 345 code | 50 blank | 25 comment | 96 complexity | 56921618ad6036696a4741db7d0c47d6 MD5 | raw file
  1. // Copyright (c) 2009-2014 The Bitcoin developers
  2. // Distributed under the MIT/X11 software license, see the accompanying
  3. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  4. #include <openssl/ecdsa.h>
  5. #include <openssl/rand.h>
  6. #include <openssl/obj_mac.h>
  7. #include "key.h"
  8. // anonymous namespace with local implementation code (OpenSSL interaction)
  9. namespace {
  10. // Generate a private key from just the secret parameter
  11. int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
  12. {
  13. int ok = 0;
  14. BN_CTX *ctx = NULL;
  15. EC_POINT *pub_key = NULL;
  16. if (!eckey) return 0;
  17. const EC_GROUP *group = EC_KEY_get0_group(eckey);
  18. if ((ctx = BN_CTX_new()) == NULL)
  19. goto err;
  20. pub_key = EC_POINT_new(group);
  21. if (pub_key == NULL)
  22. goto err;
  23. if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
  24. goto err;
  25. EC_KEY_set_private_key(eckey,priv_key);
  26. EC_KEY_set_public_key(eckey,pub_key);
  27. ok = 1;
  28. err:
  29. if (pub_key)
  30. EC_POINT_free(pub_key);
  31. if (ctx != NULL)
  32. BN_CTX_free(ctx);
  33. return(ok);
  34. }
  35. // Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
  36. // recid selects which key is recovered
  37. // if check is non-zero, additional checks are performed
  38. int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)
  39. {
  40. if (!eckey) return 0;
  41. int ret = 0;
  42. BN_CTX *ctx = NULL;
  43. BIGNUM *x = NULL;
  44. BIGNUM *e = NULL;
  45. BIGNUM *order = NULL;
  46. BIGNUM *sor = NULL;
  47. BIGNUM *eor = NULL;
  48. BIGNUM *field = NULL;
  49. EC_POINT *R = NULL;
  50. EC_POINT *O = NULL;
  51. EC_POINT *Q = NULL;
  52. BIGNUM *rr = NULL;
  53. BIGNUM *zero = NULL;
  54. int n = 0;
  55. int i = recid / 2;
  56. const EC_GROUP *group = EC_KEY_get0_group(eckey);
  57. if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
  58. BN_CTX_start(ctx);
  59. order = BN_CTX_get(ctx);
  60. if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
  61. x = BN_CTX_get(ctx);
  62. if (!BN_copy(x, order)) { ret=-1; goto err; }
  63. if (!BN_mul_word(x, i)) { ret=-1; goto err; }
  64. if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }
  65. field = BN_CTX_get(ctx);
  66. if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
  67. if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
  68. if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
  69. if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
  70. if (check)
  71. {
  72. if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
  73. if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
  74. if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
  75. }
  76. if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
  77. n = EC_GROUP_get_degree(group);
  78. e = BN_CTX_get(ctx);
  79. if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
  80. if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
  81. zero = BN_CTX_get(ctx);
  82. if (!BN_zero(zero)) { ret=-1; goto err; }
  83. if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
  84. rr = BN_CTX_get(ctx);
  85. if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }
  86. sor = BN_CTX_get(ctx);
  87. if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }
  88. eor = BN_CTX_get(ctx);
  89. if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
  90. if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
  91. if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
  92. ret = 1;
  93. err:
  94. if (ctx) {
  95. BN_CTX_end(ctx);
  96. BN_CTX_free(ctx);
  97. }
  98. if (R != NULL) EC_POINT_free(R);
  99. if (O != NULL) EC_POINT_free(O);
  100. if (Q != NULL) EC_POINT_free(Q);
  101. return ret;
  102. }
  103. // RAII Wrapper around OpenSSL's EC_KEY
  104. class CECKey {
  105. private:
  106. EC_KEY *pkey;
  107. public:
  108. CECKey() {
  109. pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
  110. assert(pkey != NULL);
  111. }
  112. ~CECKey() {
  113. EC_KEY_free(pkey);
  114. }
  115. void GetSecretBytes(unsigned char vch[32]) const {
  116. const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
  117. assert(bn);
  118. int nBytes = BN_num_bytes(bn);
  119. int n=BN_bn2bin(bn,&vch[32 - nBytes]);
  120. assert(n == nBytes);
  121. memset(vch, 0, 32 - nBytes);
  122. }
  123. void SetSecretBytes(const unsigned char vch[32]) {
  124. BIGNUM bn;
  125. BN_init(&bn);
  126. assert(BN_bin2bn(vch, 32, &bn));
  127. assert(EC_KEY_regenerate_key(pkey, &bn));
  128. BN_clear_free(&bn);
  129. }
  130. void GetPrivKey(CPrivKey &privkey, bool fCompressed) {
  131. EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
  132. int nSize = i2d_ECPrivateKey(pkey, NULL);
  133. assert(nSize);
  134. privkey.resize(nSize);
  135. unsigned char* pbegin = &privkey[0];
  136. int nSize2 = i2d_ECPrivateKey(pkey, &pbegin);
  137. assert(nSize == nSize2);
  138. }
  139. bool SetPrivKey(const CPrivKey &privkey) {
  140. const unsigned char* pbegin = &privkey[0];
  141. if (d2i_ECPrivateKey(&pkey, &pbegin, privkey.size())) {
  142. // d2i_ECPrivateKey returns true if parsing succeeds.
  143. // This doesn't necessarily mean the key is valid.
  144. if (EC_KEY_check_key(pkey))
  145. return true;
  146. }
  147. return false;
  148. }
  149. void GetPubKey(CPubKey &pubkey, bool fCompressed) {
  150. EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
  151. int nSize = i2o_ECPublicKey(pkey, NULL);
  152. assert(nSize);
  153. assert(nSize <= 65);
  154. unsigned char c[65];
  155. unsigned char *pbegin = c;
  156. int nSize2 = i2o_ECPublicKey(pkey, &pbegin);
  157. assert(nSize == nSize2);
  158. pubkey.Set(&c[0], &c[nSize]);
  159. }
  160. bool SetPubKey(const CPubKey &pubkey) {
  161. const unsigned char* pbegin = pubkey.begin();
  162. return o2i_ECPublicKey(&pkey, &pbegin, pubkey.size());
  163. }
  164. bool Sign(const uint256 &hash, std::vector<unsigned char>& vchSig) {
  165. unsigned int nSize = ECDSA_size(pkey);
  166. vchSig.resize(nSize); // Make sure it is big enough
  167. assert(ECDSA_sign(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], &nSize, pkey));
  168. vchSig.resize(nSize); // Shrink to fit actual size
  169. return true;
  170. }
  171. bool Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) {
  172. if (vchSig.empty())
  173. return false;
  174. // New versions of OpenSSL will reject non-canonical DER signatures. de/re-serialize first.
  175. unsigned char *norm_der = NULL;
  176. ECDSA_SIG *norm_sig = ECDSA_SIG_new();
  177. const unsigned char* sigptr = &vchSig[0];
  178. assert(norm_sig);
  179. if (d2i_ECDSA_SIG(&norm_sig, &sigptr, vchSig.size()) == NULL)
  180. {
  181. /* As of OpenSSL 1.0.0p d2i_ECDSA_SIG frees and nulls the pointer on
  182. * error. But OpenSSL's own use of this function redundantly frees the
  183. * result. As ECDSA_SIG_free(NULL) is a no-op, and in the absence of a
  184. * clear contract for the function behaving the same way is more
  185. * conservative.
  186. */
  187. ECDSA_SIG_free(norm_sig);
  188. return false;
  189. }
  190. int derlen = i2d_ECDSA_SIG(norm_sig, &norm_der);
  191. ECDSA_SIG_free(norm_sig);
  192. if (derlen <= 0)
  193. return false;
  194. // -1 = error, 0 = bad sig, 1 = good
  195. bool ret = ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), norm_der, derlen, pkey) == 1;
  196. OPENSSL_free(norm_der);
  197. return ret;
  198. }
  199. bool SignCompact(const uint256 &hash, unsigned char *p64, int &rec) {
  200. bool fOk = false;
  201. ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
  202. if (sig==NULL)
  203. return false;
  204. memset(p64, 0, 64);
  205. int nBitsR = BN_num_bits(sig->r);
  206. int nBitsS = BN_num_bits(sig->s);
  207. if (nBitsR <= 256 && nBitsS <= 256) {
  208. CPubKey pubkey;
  209. GetPubKey(pubkey, true);
  210. for (int i=0; i<4; i++) {
  211. CECKey keyRec;
  212. if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1) {
  213. CPubKey pubkeyRec;
  214. keyRec.GetPubKey(pubkeyRec, true);
  215. if (pubkeyRec == pubkey) {
  216. rec = i;
  217. fOk = true;
  218. break;
  219. }
  220. }
  221. }
  222. assert(fOk);
  223. BN_bn2bin(sig->r,&p64[32-(nBitsR+7)/8]);
  224. BN_bn2bin(sig->s,&p64[64-(nBitsS+7)/8]);
  225. }
  226. ECDSA_SIG_free(sig);
  227. return fOk;
  228. }
  229. // reconstruct public key from a compact signature
  230. // This is only slightly more CPU intensive than just verifying it.
  231. // If this function succeeds, the recovered public key is guaranteed to be valid
  232. // (the signature is a valid signature of the given data for that key)
  233. bool Recover(const uint256 &hash, const unsigned char *p64, int rec)
  234. {
  235. if (rec<0 || rec>=3)
  236. return false;
  237. ECDSA_SIG *sig = ECDSA_SIG_new();
  238. BN_bin2bn(&p64[0], 32, sig->r);
  239. BN_bin2bn(&p64[32], 32, sig->s);
  240. bool ret = ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), rec, 0) == 1;
  241. ECDSA_SIG_free(sig);
  242. return ret;
  243. }
  244. };
  245. }; // end of anonymous namespace
  246. bool CKey::Check(const unsigned char *vch) {
  247. // Do not convert to OpenSSL's data structures for range-checking keys,
  248. // it's easy enough to do directly.
  249. static const unsigned char vchMax[32] = {
  250. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  251. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE,
  252. 0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,
  253. 0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x40
  254. };
  255. bool fIsZero = true;
  256. for (int i=0; i<32 && fIsZero; i++)
  257. if (vch[i] != 0)
  258. fIsZero = false;
  259. if (fIsZero)
  260. return false;
  261. for (int i=0; i<32; i++) {
  262. if (vch[i] < vchMax[i])
  263. return true;
  264. if (vch[i] > vchMax[i])
  265. return false;
  266. }
  267. return true;
  268. }
  269. void CKey::MakeNewKey(bool fCompressedIn) {
  270. do {
  271. RAND_bytes(vch, sizeof(vch));
  272. } while (!Check(vch));
  273. fValid = true;
  274. fCompressed = fCompressedIn;
  275. }
  276. bool CKey::SetPrivKey(const CPrivKey &privkey, bool fCompressedIn) {
  277. CECKey key;
  278. if (!key.SetPrivKey(privkey))
  279. return false;
  280. key.GetSecretBytes(vch);
  281. fCompressed = fCompressedIn;
  282. fValid = true;
  283. return true;
  284. }
  285. CPrivKey CKey::GetPrivKey() const {
  286. assert(fValid);
  287. CECKey key;
  288. key.SetSecretBytes(vch);
  289. CPrivKey privkey;
  290. key.GetPrivKey(privkey, fCompressed);
  291. return privkey;
  292. }
  293. CPubKey CKey::GetPubKey() const {
  294. assert(fValid);
  295. CECKey key;
  296. key.SetSecretBytes(vch);
  297. CPubKey pubkey;
  298. key.GetPubKey(pubkey, fCompressed);
  299. return pubkey;
  300. }
  301. bool CKey::Sign(const uint256 &hash, std::vector<unsigned char>& vchSig) const {
  302. if (!fValid)
  303. return false;
  304. CECKey key;
  305. key.SetSecretBytes(vch);
  306. return key.Sign(hash, vchSig);
  307. }
  308. bool CKey::SignCompact(const uint256 &hash, std::vector<unsigned char>& vchSig) const {
  309. if (!fValid)
  310. return false;
  311. CECKey key;
  312. key.SetSecretBytes(vch);
  313. vchSig.resize(65);
  314. int rec = -1;
  315. if (!key.SignCompact(hash, &vchSig[1], rec))
  316. return false;
  317. assert(rec != -1);
  318. vchSig[0] = 27 + rec + (fCompressed ? 4 : 0);
  319. return true;
  320. }
  321. bool CPubKey::Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) const {
  322. if (!IsValid())
  323. return false;
  324. CECKey key;
  325. if (!key.SetPubKey(*this))
  326. return false;
  327. if (!key.Verify(hash, vchSig))
  328. return false;
  329. return true;
  330. }
  331. bool CPubKey::RecoverCompact(const uint256 &hash, const std::vector<unsigned char>& vchSig) {
  332. if (vchSig.size() != 65)
  333. return false;
  334. CECKey key;
  335. if (!key.Recover(hash, &vchSig[1], (vchSig[0] - 27) & ~4))
  336. return false;
  337. key.GetPubKey(*this, (vchSig[0] - 27) & 4);
  338. return true;
  339. }
  340. bool CPubKey::VerifyCompact(const uint256 &hash, const std::vector<unsigned char>& vchSig) const {
  341. if (!IsValid())
  342. return false;
  343. if (vchSig.size() != 65)
  344. return false;
  345. CECKey key;
  346. if (!key.Recover(hash, &vchSig[1], (vchSig[0] - 27) & ~4))
  347. return false;
  348. CPubKey pubkeyRec;
  349. key.GetPubKey(pubkeyRec, IsCompressed());
  350. if (*this != pubkeyRec)
  351. return false;
  352. return true;
  353. }
  354. bool CPubKey::IsFullyValid() const {
  355. if (!IsValid())
  356. return false;
  357. CECKey key;
  358. if (!key.SetPubKey(*this))
  359. return false;
  360. return true;
  361. }
  362. bool CPubKey::Decompress() {
  363. if (!IsValid())
  364. return false;
  365. CECKey key;
  366. if (!key.SetPubKey(*this))
  367. return false;
  368. key.GetPubKey(*this, false);
  369. return true;
  370. }