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.

key.cpp 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. // Copyright (c) 2009-2013 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 "key.h"
  5. #include <openssl/bn.h>
  6. #include <openssl/ecdsa.h>
  7. #include <openssl/obj_mac.h>
  8. #include <openssl/rand.h>
  9. // anonymous namespace with local implementation code (OpenSSL interaction)
  10. namespace {
  11. // Generate a private key from just the secret parameter
  12. int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
  13. {
  14. int ok = 0;
  15. BN_CTX *ctx = NULL;
  16. EC_POINT *pub_key = NULL;
  17. if (!eckey) return 0;
  18. const EC_GROUP *group = EC_KEY_get0_group(eckey);
  19. if ((ctx = BN_CTX_new()) == NULL)
  20. goto err;
  21. pub_key = EC_POINT_new(group);
  22. if (pub_key == NULL)
  23. goto err;
  24. if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
  25. goto err;
  26. EC_KEY_set_private_key(eckey,priv_key);
  27. EC_KEY_set_public_key(eckey,pub_key);
  28. ok = 1;
  29. err:
  30. if (pub_key)
  31. EC_POINT_free(pub_key);
  32. if (ctx != NULL)
  33. BN_CTX_free(ctx);
  34. return(ok);
  35. }
  36. // Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
  37. // recid selects which key is recovered
  38. // if check is non-zero, additional checks are performed
  39. int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)
  40. {
  41. if (!eckey) return 0;
  42. int ret = 0;
  43. BN_CTX *ctx = NULL;
  44. BIGNUM *x = NULL;
  45. BIGNUM *e = NULL;
  46. BIGNUM *order = NULL;
  47. BIGNUM *sor = NULL;
  48. BIGNUM *eor = NULL;
  49. BIGNUM *field = NULL;
  50. EC_POINT *R = NULL;
  51. EC_POINT *O = NULL;
  52. EC_POINT *Q = NULL;
  53. BIGNUM *rr = NULL;
  54. BIGNUM *zero = NULL;
  55. int n = 0;
  56. int i = recid / 2;
  57. const EC_GROUP *group = EC_KEY_get0_group(eckey);
  58. if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
  59. BN_CTX_start(ctx);
  60. order = BN_CTX_get(ctx);
  61. if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
  62. x = BN_CTX_get(ctx);
  63. if (!BN_copy(x, order)) { ret=-1; goto err; }
  64. if (!BN_mul_word(x, i)) { ret=-1; goto err; }
  65. if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }
  66. field = BN_CTX_get(ctx);
  67. if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
  68. if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
  69. if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
  70. if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
  71. if (check)
  72. {
  73. if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
  74. if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
  75. if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
  76. }
  77. if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
  78. n = EC_GROUP_get_degree(group);
  79. e = BN_CTX_get(ctx);
  80. if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
  81. if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
  82. zero = BN_CTX_get(ctx);
  83. if (!BN_zero(zero)) { ret=-1; goto err; }
  84. if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
  85. rr = BN_CTX_get(ctx);
  86. if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }
  87. sor = BN_CTX_get(ctx);
  88. if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }
  89. eor = BN_CTX_get(ctx);
  90. if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
  91. if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
  92. if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
  93. ret = 1;
  94. err:
  95. if (ctx) {
  96. BN_CTX_end(ctx);
  97. BN_CTX_free(ctx);
  98. }
  99. if (R != NULL) EC_POINT_free(R);
  100. if (O != NULL) EC_POINT_free(O);
  101. if (Q != NULL) EC_POINT_free(Q);
  102. return ret;
  103. }
  104. // RAII Wrapper around OpenSSL's EC_KEY
  105. class CECKey {
  106. private:
  107. EC_KEY *pkey;
  108. public:
  109. CECKey() {
  110. pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
  111. assert(pkey != NULL);
  112. }
  113. ~CECKey() {
  114. EC_KEY_free(pkey);
  115. }
  116. void GetSecretBytes(unsigned char vch[32]) const {
  117. const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
  118. assert(bn);
  119. int nBytes = BN_num_bytes(bn);
  120. int n=BN_bn2bin(bn,&vch[32 - nBytes]);
  121. assert(n == nBytes);
  122. memset(vch, 0, 32 - nBytes);
  123. }
  124. void SetSecretBytes(const unsigned char vch[32]) {
  125. bool ret;
  126. BIGNUM bn;
  127. BN_init(&bn);
  128. ret = BN_bin2bn(vch, 32, &bn);
  129. assert(ret);
  130. ret = EC_KEY_regenerate_key(pkey, &bn);
  131. assert(ret);
  132. BN_clear_free(&bn);
  133. }
  134. void GetPrivKey(CPrivKey &privkey, bool fCompressed) {
  135. EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
  136. int nSize = i2d_ECPrivateKey(pkey, NULL);
  137. assert(nSize);
  138. privkey.resize(nSize);
  139. unsigned char* pbegin = &privkey[0];
  140. int nSize2 = i2d_ECPrivateKey(pkey, &pbegin);
  141. assert(nSize == nSize2);
  142. }
  143. bool SetPrivKey(const CPrivKey &privkey, bool fSkipCheck=false) {
  144. const unsigned char* pbegin = &privkey[0];
  145. if (d2i_ECPrivateKey(&pkey, &pbegin, privkey.size())) {
  146. if(fSkipCheck)
  147. return true;
  148. // d2i_ECPrivateKey returns true if parsing succeeds.
  149. // This doesn't necessarily mean the key is valid.
  150. if (EC_KEY_check_key(pkey))
  151. return true;
  152. }
  153. return false;
  154. }
  155. void GetPubKey(CPubKey &pubkey, bool fCompressed) {
  156. EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
  157. int nSize = i2o_ECPublicKey(pkey, NULL);
  158. assert(nSize);
  159. assert(nSize <= 65);
  160. unsigned char c[65];
  161. unsigned char *pbegin = c;
  162. int nSize2 = i2o_ECPublicKey(pkey, &pbegin);
  163. assert(nSize == nSize2);
  164. pubkey.Set(&c[0], &c[nSize]);
  165. }
  166. bool SetPubKey(const CPubKey &pubkey) {
  167. const unsigned char* pbegin = pubkey.begin();
  168. return o2i_ECPublicKey(&pkey, &pbegin, pubkey.size());
  169. }
  170. bool Sign(const uint256 &hash, std::vector<unsigned char>& vchSig) {
  171. vchSig.clear();
  172. ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
  173. if (sig == NULL)
  174. return false;
  175. BN_CTX *ctx = BN_CTX_new();
  176. BN_CTX_start(ctx);
  177. const EC_GROUP *group = EC_KEY_get0_group(pkey);
  178. BIGNUM *order = BN_CTX_get(ctx);
  179. BIGNUM *halforder = BN_CTX_get(ctx);
  180. EC_GROUP_get_order(group, order, ctx);
  181. BN_rshift1(halforder, order);
  182. if (BN_cmp(sig->s, halforder) > 0) {
  183. // enforce low S values, by negating the value (modulo the order) if above order/2.
  184. BN_sub(sig->s, order, sig->s);
  185. }
  186. BN_CTX_end(ctx);
  187. BN_CTX_free(ctx);
  188. unsigned int nSize = ECDSA_size(pkey);
  189. vchSig.resize(nSize); // Make sure it is big enough
  190. unsigned char *pos = &vchSig[0];
  191. nSize = i2d_ECDSA_SIG(sig, &pos);
  192. ECDSA_SIG_free(sig);
  193. vchSig.resize(nSize); // Shrink to fit actual size
  194. return true;
  195. }
  196. bool Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) {
  197. // -1 = error, 0 = bad sig, 1 = good
  198. if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1)
  199. return false;
  200. return true;
  201. }
  202. bool SignCompact(const uint256 &hash, unsigned char *p64, int &rec) {
  203. bool fOk = false;
  204. ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
  205. if (sig==NULL)
  206. return false;
  207. memset(p64, 0, 64);
  208. int nBitsR = BN_num_bits(sig->r);
  209. int nBitsS = BN_num_bits(sig->s);
  210. if (nBitsR <= 256 && nBitsS <= 256) {
  211. CPubKey pubkey;
  212. GetPubKey(pubkey, true);
  213. for (int i=0; i<4; i++) {
  214. CECKey keyRec;
  215. if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1) {
  216. CPubKey pubkeyRec;
  217. keyRec.GetPubKey(pubkeyRec, true);
  218. if (pubkeyRec == pubkey) {
  219. rec = i;
  220. fOk = true;
  221. break;
  222. }
  223. }
  224. }
  225. assert(fOk);
  226. BN_bn2bin(sig->r,&p64[32-(nBitsR+7)/8]);
  227. BN_bn2bin(sig->s,&p64[64-(nBitsS+7)/8]);
  228. }
  229. ECDSA_SIG_free(sig);
  230. return fOk;
  231. }
  232. // reconstruct public key from a compact signature
  233. // This is only slightly more CPU intensive than just verifying it.
  234. // If this function succeeds, the recovered public key is guaranteed to be valid
  235. // (the signature is a valid signature of the given data for that key)
  236. bool Recover(const uint256 &hash, const unsigned char *p64, int rec)
  237. {
  238. if (rec<0 || rec>=3)
  239. return false;
  240. ECDSA_SIG *sig = ECDSA_SIG_new();
  241. BN_bin2bn(&p64[0], 32, sig->r);
  242. BN_bin2bn(&p64[32], 32, sig->s);
  243. bool ret = ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), rec, 0) == 1;
  244. ECDSA_SIG_free(sig);
  245. return ret;
  246. }
  247. static bool TweakSecret(unsigned char vchSecretOut[32], const unsigned char vchSecretIn[32], const unsigned char vchTweak[32])
  248. {
  249. bool ret = true;
  250. BN_CTX *ctx = BN_CTX_new();
  251. BN_CTX_start(ctx);
  252. BIGNUM *bnSecret = BN_CTX_get(ctx);
  253. BIGNUM *bnTweak = BN_CTX_get(ctx);
  254. BIGNUM *bnOrder = BN_CTX_get(ctx);
  255. EC_GROUP *group = EC_GROUP_new_by_curve_name(NID_secp256k1);
  256. EC_GROUP_get_order(group, bnOrder, ctx); // what a grossly inefficient way to get the (constant) group order...
  257. BN_bin2bn(vchTweak, 32, bnTweak);
  258. if (BN_cmp(bnTweak, bnOrder) >= 0)
  259. ret = false; // extremely unlikely
  260. BN_bin2bn(vchSecretIn, 32, bnSecret);
  261. BN_add(bnSecret, bnSecret, bnTweak);
  262. BN_nnmod(bnSecret, bnSecret, bnOrder, ctx);
  263. if (BN_is_zero(bnSecret))
  264. ret = false; // ridiculously unlikely
  265. int nBits = BN_num_bits(bnSecret);
  266. memset(vchSecretOut, 0, 32);
  267. BN_bn2bin(bnSecret, &vchSecretOut[32-(nBits+7)/8]);
  268. EC_GROUP_free(group);
  269. BN_CTX_end(ctx);
  270. BN_CTX_free(ctx);
  271. return ret;
  272. }
  273. bool TweakPublic(const unsigned char vchTweak[32]) {
  274. bool ret = true;
  275. BN_CTX *ctx = BN_CTX_new();
  276. BN_CTX_start(ctx);
  277. BIGNUM *bnTweak = BN_CTX_get(ctx);
  278. BIGNUM *bnOrder = BN_CTX_get(ctx);
  279. BIGNUM *bnOne = BN_CTX_get(ctx);
  280. const EC_GROUP *group = EC_KEY_get0_group(pkey);
  281. EC_GROUP_get_order(group, bnOrder, ctx); // what a grossly inefficient way to get the (constant) group order...
  282. BN_bin2bn(vchTweak, 32, bnTweak);
  283. if (BN_cmp(bnTweak, bnOrder) >= 0)
  284. ret = false; // extremely unlikely
  285. EC_POINT *point = EC_POINT_dup(EC_KEY_get0_public_key(pkey), group);
  286. BN_one(bnOne);
  287. EC_POINT_mul(group, point, bnTweak, point, bnOne, ctx);
  288. if (EC_POINT_is_at_infinity(group, point))
  289. ret = false; // ridiculously unlikely
  290. EC_KEY_set_public_key(pkey, point);
  291. EC_POINT_free(point);
  292. BN_CTX_end(ctx);
  293. BN_CTX_free(ctx);
  294. return ret;
  295. }
  296. };
  297. }; // end of anonymous namespace
  298. bool CKey::Check(const unsigned char *vch) {
  299. // Do not convert to OpenSSL's data structures for range-checking keys,
  300. // it's easy enough to do directly.
  301. static const unsigned char vchMax[32] = {
  302. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  303. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE,
  304. 0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,
  305. 0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x40
  306. };
  307. bool fIsZero = true;
  308. for (int i=0; i<32 && fIsZero; i++)
  309. if (vch[i] != 0)
  310. fIsZero = false;
  311. if (fIsZero)
  312. return false;
  313. for (int i=0; i<32; i++) {
  314. if (vch[i] < vchMax[i])
  315. return true;
  316. if (vch[i] > vchMax[i])
  317. return false;
  318. }
  319. return true;
  320. }
  321. void CKey::MakeNewKey(bool fCompressedIn) {
  322. do {
  323. RAND_bytes(vch, sizeof(vch));
  324. } while (!Check(vch));
  325. fValid = true;
  326. fCompressed = fCompressedIn;
  327. }
  328. bool CKey::SetPrivKey(const CPrivKey &privkey, bool fCompressedIn) {
  329. CECKey key;
  330. if (!key.SetPrivKey(privkey))
  331. return false;
  332. key.GetSecretBytes(vch);
  333. fCompressed = fCompressedIn;
  334. fValid = true;
  335. return true;
  336. }
  337. CPrivKey CKey::GetPrivKey() const {
  338. assert(fValid);
  339. CECKey key;
  340. key.SetSecretBytes(vch);
  341. CPrivKey privkey;
  342. key.GetPrivKey(privkey, fCompressed);
  343. return privkey;
  344. }
  345. CPubKey CKey::GetPubKey() const {
  346. assert(fValid);
  347. CECKey key;
  348. key.SetSecretBytes(vch);
  349. CPubKey pubkey;
  350. key.GetPubKey(pubkey, fCompressed);
  351. return pubkey;
  352. }
  353. bool CKey::Sign(const uint256 &hash, std::vector<unsigned char>& vchSig) const {
  354. if (!fValid)
  355. return false;
  356. CECKey key;
  357. key.SetSecretBytes(vch);
  358. return key.Sign(hash, vchSig);
  359. }
  360. bool CKey::SignCompact(const uint256 &hash, std::vector<unsigned char>& vchSig) const {
  361. if (!fValid)
  362. return false;
  363. CECKey key;
  364. key.SetSecretBytes(vch);
  365. vchSig.resize(65);
  366. int rec = -1;
  367. if (!key.SignCompact(hash, &vchSig[1], rec))
  368. return false;
  369. assert(rec != -1);
  370. vchSig[0] = 27 + rec + (fCompressed ? 4 : 0);
  371. return true;
  372. }
  373. bool CKey::Load(CPrivKey &privkey, CPubKey &vchPubKey, bool fSkipCheck=false) {
  374. CECKey key;
  375. if (!key.SetPrivKey(privkey, fSkipCheck))
  376. return false;
  377. key.GetSecretBytes(vch);
  378. fCompressed = vchPubKey.IsCompressed();
  379. fValid = true;
  380. if (fSkipCheck)
  381. return true;
  382. if (GetPubKey() != vchPubKey)
  383. return false;
  384. return true;
  385. }
  386. bool CPubKey::Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) const {
  387. if (!IsValid())
  388. return false;
  389. CECKey key;
  390. if (!key.SetPubKey(*this))
  391. return false;
  392. if (!key.Verify(hash, vchSig))
  393. return false;
  394. return true;
  395. }
  396. bool CPubKey::RecoverCompact(const uint256 &hash, const std::vector<unsigned char>& vchSig) {
  397. if (vchSig.size() != 65)
  398. return false;
  399. CECKey key;
  400. if (!key.Recover(hash, &vchSig[1], (vchSig[0] - 27) & ~4))
  401. return false;
  402. key.GetPubKey(*this, (vchSig[0] - 27) & 4);
  403. return true;
  404. }
  405. bool CPubKey::VerifyCompact(const uint256 &hash, const std::vector<unsigned char>& vchSig) const {
  406. if (!IsValid())
  407. return false;
  408. if (vchSig.size() != 65)
  409. return false;
  410. CECKey key;
  411. if (!key.Recover(hash, &vchSig[1], (vchSig[0] - 27) & ~4))
  412. return false;
  413. CPubKey pubkeyRec;
  414. key.GetPubKey(pubkeyRec, IsCompressed());
  415. if (*this != pubkeyRec)
  416. return false;
  417. return true;
  418. }
  419. bool CPubKey::IsFullyValid() const {
  420. if (!IsValid())
  421. return false;
  422. CECKey key;
  423. if (!key.SetPubKey(*this))
  424. return false;
  425. return true;
  426. }
  427. bool CPubKey::Decompress() {
  428. if (!IsValid())
  429. return false;
  430. CECKey key;
  431. if (!key.SetPubKey(*this))
  432. return false;
  433. key.GetPubKey(*this, false);
  434. return true;
  435. }
  436. void static BIP32Hash(const unsigned char chainCode[32], unsigned int nChild, unsigned char header, const unsigned char data[32], unsigned char output[64]) {
  437. unsigned char num[4];
  438. num[0] = (nChild >> 24) & 0xFF;
  439. num[1] = (nChild >> 16) & 0xFF;
  440. num[2] = (nChild >> 8) & 0xFF;
  441. num[3] = (nChild >> 0) & 0xFF;
  442. HMAC_SHA512_CTX ctx;
  443. HMAC_SHA512_Init(&ctx, chainCode, 32);
  444. HMAC_SHA512_Update(&ctx, &header, 1);
  445. HMAC_SHA512_Update(&ctx, data, 32);
  446. HMAC_SHA512_Update(&ctx, num, 4);
  447. HMAC_SHA512_Final(output, &ctx);
  448. }
  449. bool CKey::Derive(CKey& keyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const {
  450. assert(IsValid());
  451. assert(IsCompressed());
  452. unsigned char out[64];
  453. LockObject(out);
  454. if ((nChild >> 31) == 0) {
  455. CPubKey pubkey = GetPubKey();
  456. assert(pubkey.begin() + 33 == pubkey.end());
  457. BIP32Hash(cc, nChild, *pubkey.begin(), pubkey.begin()+1, out);
  458. } else {
  459. assert(begin() + 32 == end());
  460. BIP32Hash(cc, nChild, 0, begin(), out);
  461. }
  462. memcpy(ccChild, out+32, 32);
  463. bool ret = CECKey::TweakSecret((unsigned char*)keyChild.begin(), begin(), out);
  464. UnlockObject(out);
  465. keyChild.fCompressed = true;
  466. keyChild.fValid = ret;
  467. return ret;
  468. }
  469. bool CPubKey::Derive(CPubKey& pubkeyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const {
  470. assert(IsValid());
  471. assert((nChild >> 31) == 0);
  472. assert(begin() + 33 == end());
  473. unsigned char out[64];
  474. BIP32Hash(cc, nChild, *begin(), begin()+1, out);
  475. memcpy(ccChild, out+32, 32);
  476. CECKey key;
  477. bool ret = key.SetPubKey(*this);
  478. ret &= key.TweakPublic(out);
  479. key.GetPubKey(pubkeyChild, true);
  480. return ret;
  481. }
  482. bool CExtKey::Derive(CExtKey &out, unsigned int nChild) const {
  483. out.nDepth = nDepth + 1;
  484. CKeyID id = key.GetPubKey().GetID();
  485. memcpy(&out.vchFingerprint[0], &id, 4);
  486. out.nChild = nChild;
  487. return key.Derive(out.key, out.vchChainCode, nChild, vchChainCode);
  488. }
  489. void CExtKey::SetMaster(const unsigned char *seed, unsigned int nSeedLen) {
  490. static const char hashkey[] = {'B','i','t','c','o','i','n',' ','s','e','e','d'};
  491. HMAC_SHA512_CTX ctx;
  492. HMAC_SHA512_Init(&ctx, hashkey, sizeof(hashkey));
  493. HMAC_SHA512_Update(&ctx, seed, nSeedLen);
  494. unsigned char out[64];
  495. LockObject(out);
  496. HMAC_SHA512_Final(out, &ctx);
  497. key.Set(&out[0], &out[32], true);
  498. memcpy(vchChainCode, &out[32], 32);
  499. UnlockObject(out);
  500. nDepth = 0;
  501. nChild = 0;
  502. memset(vchFingerprint, 0, sizeof(vchFingerprint));
  503. }
  504. CExtPubKey CExtKey::Neuter() const {
  505. CExtPubKey ret;
  506. ret.nDepth = nDepth;
  507. memcpy(&ret.vchFingerprint[0], &vchFingerprint[0], 4);
  508. ret.nChild = nChild;
  509. ret.pubkey = key.GetPubKey();
  510. memcpy(&ret.vchChainCode[0], &vchChainCode[0], 32);
  511. return ret;
  512. }
  513. void CExtKey::Encode(unsigned char code[74]) const {
  514. code[0] = nDepth;
  515. memcpy(code+1, vchFingerprint, 4);
  516. code[5] = (nChild >> 24) & 0xFF; code[6] = (nChild >> 16) & 0xFF;
  517. code[7] = (nChild >> 8) & 0xFF; code[8] = (nChild >> 0) & 0xFF;
  518. memcpy(code+9, vchChainCode, 32);
  519. code[41] = 0;
  520. assert(key.size() == 32);
  521. memcpy(code+42, key.begin(), 32);
  522. }
  523. void CExtKey::Decode(const unsigned char code[74]) {
  524. nDepth = code[0];
  525. memcpy(vchFingerprint, code+1, 4);
  526. nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8];
  527. memcpy(vchChainCode, code+9, 32);
  528. key.Set(code+42, code+74, true);
  529. }
  530. void CExtPubKey::Encode(unsigned char code[74]) const {
  531. code[0] = nDepth;
  532. memcpy(code+1, vchFingerprint, 4);
  533. code[5] = (nChild >> 24) & 0xFF; code[6] = (nChild >> 16) & 0xFF;
  534. code[7] = (nChild >> 8) & 0xFF; code[8] = (nChild >> 0) & 0xFF;
  535. memcpy(code+9, vchChainCode, 32);
  536. assert(pubkey.size() == 33);
  537. memcpy(code+41, pubkey.begin(), 33);
  538. }
  539. void CExtPubKey::Decode(const unsigned char code[74]) {
  540. nDepth = code[0];
  541. memcpy(vchFingerprint, code+1, 4);
  542. nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8];
  543. memcpy(vchChainCode, code+9, 32);
  544. pubkey.Set(code+41, code+74);
  545. }
  546. bool CExtPubKey::Derive(CExtPubKey &out, unsigned int nChild) const {
  547. out.nDepth = nDepth + 1;
  548. CKeyID id = pubkey.GetID();
  549. memcpy(&out.vchFingerprint[0], &id, 4);
  550. out.nChild = nChild;
  551. return pubkey.Derive(out.pubkey, out.vchChainCode, nChild, vchChainCode);
  552. }