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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. // Copyright (c) 2009-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 "key.h"
  5. #include "arith_uint256.h"
  6. #include "crypto/common.h"
  7. #include "crypto/hmac_sha512.h"
  8. #include "pubkey.h"
  9. #include "random.h"
  10. #include <secp256k1.h>
  11. #include <secp256k1_recovery.h>
  12. static secp256k1_context* secp256k1_context_sign = nullptr;
  13. /** These functions are taken from the libsecp256k1 distribution and are very ugly. */
  14. static int ec_privkey_import_der(const secp256k1_context* ctx, unsigned char *out32, const unsigned char *privkey, size_t privkeylen) {
  15. const unsigned char *end = privkey + privkeylen;
  16. int lenb = 0;
  17. int len = 0;
  18. memset(out32, 0, 32);
  19. /* sequence header */
  20. if (end < privkey+1 || *privkey != 0x30) {
  21. return 0;
  22. }
  23. privkey++;
  24. /* sequence length constructor */
  25. if (end < privkey+1 || !(*privkey & 0x80)) {
  26. return 0;
  27. }
  28. lenb = *privkey & ~0x80; privkey++;
  29. if (lenb < 1 || lenb > 2) {
  30. return 0;
  31. }
  32. if (end < privkey+lenb) {
  33. return 0;
  34. }
  35. /* sequence length */
  36. len = privkey[lenb-1] | (lenb > 1 ? privkey[lenb-2] << 8 : 0);
  37. privkey += lenb;
  38. if (end < privkey+len) {
  39. return 0;
  40. }
  41. /* sequence element 0: version number (=1) */
  42. if (end < privkey+3 || privkey[0] != 0x02 || privkey[1] != 0x01 || privkey[2] != 0x01) {
  43. return 0;
  44. }
  45. privkey += 3;
  46. /* sequence element 1: octet string, up to 32 bytes */
  47. if (end < privkey+2 || privkey[0] != 0x04 || privkey[1] > 0x20 || end < privkey+2+privkey[1]) {
  48. return 0;
  49. }
  50. memcpy(out32 + 32 - privkey[1], privkey + 2, privkey[1]);
  51. if (!secp256k1_ec_seckey_verify(ctx, out32)) {
  52. memset(out32, 0, 32);
  53. return 0;
  54. }
  55. return 1;
  56. }
  57. static int ec_privkey_export_der(const secp256k1_context *ctx, unsigned char *privkey, size_t *privkeylen, const unsigned char *key32, int compressed) {
  58. secp256k1_pubkey pubkey;
  59. size_t pubkeylen = 0;
  60. if (!secp256k1_ec_pubkey_create(ctx, &pubkey, key32)) {
  61. *privkeylen = 0;
  62. return 0;
  63. }
  64. if (compressed) {
  65. static const unsigned char begin[] = {
  66. 0x30,0x81,0xD3,0x02,0x01,0x01,0x04,0x20
  67. };
  68. static const unsigned char middle[] = {
  69. 0xA0,0x81,0x85,0x30,0x81,0x82,0x02,0x01,0x01,0x30,0x2C,0x06,0x07,0x2A,0x86,0x48,
  70. 0xCE,0x3D,0x01,0x01,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  71. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  72. 0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F,0x30,0x06,0x04,0x01,0x00,0x04,0x01,0x07,0x04,
  73. 0x21,0x02,0x79,0xBE,0x66,0x7E,0xF9,0xDC,0xBB,0xAC,0x55,0xA0,0x62,0x95,0xCE,0x87,
  74. 0x0B,0x07,0x02,0x9B,0xFC,0xDB,0x2D,0xCE,0x28,0xD9,0x59,0xF2,0x81,0x5B,0x16,0xF8,
  75. 0x17,0x98,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  76. 0xFF,0xFF,0xFF,0xFF,0xFE,0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,0xBF,0xD2,0x5E,
  77. 0x8C,0xD0,0x36,0x41,0x41,0x02,0x01,0x01,0xA1,0x24,0x03,0x22,0x00
  78. };
  79. unsigned char *ptr = privkey;
  80. memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin);
  81. memcpy(ptr, key32, 32); ptr += 32;
  82. memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle);
  83. pubkeylen = 33;
  84. secp256k1_ec_pubkey_serialize(ctx, ptr, &pubkeylen, &pubkey, SECP256K1_EC_COMPRESSED);
  85. ptr += pubkeylen;
  86. *privkeylen = ptr - privkey;
  87. } else {
  88. static const unsigned char begin[] = {
  89. 0x30,0x82,0x01,0x13,0x02,0x01,0x01,0x04,0x20
  90. };
  91. static const unsigned char middle[] = {
  92. 0xA0,0x81,0xA5,0x30,0x81,0xA2,0x02,0x01,0x01,0x30,0x2C,0x06,0x07,0x2A,0x86,0x48,
  93. 0xCE,0x3D,0x01,0x01,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  94. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  95. 0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F,0x30,0x06,0x04,0x01,0x00,0x04,0x01,0x07,0x04,
  96. 0x41,0x04,0x79,0xBE,0x66,0x7E,0xF9,0xDC,0xBB,0xAC,0x55,0xA0,0x62,0x95,0xCE,0x87,
  97. 0x0B,0x07,0x02,0x9B,0xFC,0xDB,0x2D,0xCE,0x28,0xD9,0x59,0xF2,0x81,0x5B,0x16,0xF8,
  98. 0x17,0x98,0x48,0x3A,0xDA,0x77,0x26,0xA3,0xC4,0x65,0x5D,0xA4,0xFB,0xFC,0x0E,0x11,
  99. 0x08,0xA8,0xFD,0x17,0xB4,0x48,0xA6,0x85,0x54,0x19,0x9C,0x47,0xD0,0x8F,0xFB,0x10,
  100. 0xD4,0xB8,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  101. 0xFF,0xFF,0xFF,0xFF,0xFE,0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,0xBF,0xD2,0x5E,
  102. 0x8C,0xD0,0x36,0x41,0x41,0x02,0x01,0x01,0xA1,0x44,0x03,0x42,0x00
  103. };
  104. unsigned char *ptr = privkey;
  105. memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin);
  106. memcpy(ptr, key32, 32); ptr += 32;
  107. memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle);
  108. pubkeylen = 65;
  109. secp256k1_ec_pubkey_serialize(ctx, ptr, &pubkeylen, &pubkey, SECP256K1_EC_UNCOMPRESSED);
  110. ptr += pubkeylen;
  111. *privkeylen = ptr - privkey;
  112. }
  113. return 1;
  114. }
  115. bool CKey::Check(const unsigned char *vch) {
  116. return secp256k1_ec_seckey_verify(secp256k1_context_sign, vch);
  117. }
  118. void CKey::MakeNewKey(bool fCompressedIn) {
  119. do {
  120. GetStrongRandBytes(keydata.data(), keydata.size());
  121. } while (!Check(keydata.data()));
  122. fValid = true;
  123. fCompressed = fCompressedIn;
  124. }
  125. CPrivKey CKey::GetPrivKey() const {
  126. assert(fValid);
  127. CPrivKey privkey;
  128. int ret;
  129. size_t privkeylen;
  130. privkey.resize(279);
  131. privkeylen = 279;
  132. ret = ec_privkey_export_der(secp256k1_context_sign, (unsigned char*) privkey.data(), &privkeylen, begin(), fCompressed ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED);
  133. assert(ret);
  134. privkey.resize(privkeylen);
  135. return privkey;
  136. }
  137. CPubKey CKey::GetPubKey() const {
  138. assert(fValid);
  139. secp256k1_pubkey pubkey;
  140. size_t clen = 65;
  141. CPubKey result;
  142. int ret = secp256k1_ec_pubkey_create(secp256k1_context_sign, &pubkey, begin());
  143. assert(ret);
  144. secp256k1_ec_pubkey_serialize(secp256k1_context_sign, (unsigned char*)result.begin(), &clen, &pubkey, fCompressed ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED);
  145. assert(result.size() == clen);
  146. assert(result.IsValid());
  147. return result;
  148. }
  149. bool CKey::Sign(const uint256 &hash, std::vector<unsigned char>& vchSig, uint32_t test_case) const {
  150. if (!fValid)
  151. return false;
  152. vchSig.resize(72);
  153. size_t nSigLen = 72;
  154. unsigned char extra_entropy[32] = {0};
  155. WriteLE32(extra_entropy, test_case);
  156. secp256k1_ecdsa_signature sig;
  157. int ret = secp256k1_ecdsa_sign(secp256k1_context_sign, &sig, hash.begin(), begin(), secp256k1_nonce_function_rfc6979, test_case ? extra_entropy : nullptr);
  158. assert(ret);
  159. secp256k1_ecdsa_signature_serialize_der(secp256k1_context_sign, (unsigned char*)vchSig.data(), &nSigLen, &sig);
  160. vchSig.resize(nSigLen);
  161. return true;
  162. }
  163. bool CKey::VerifyPubKey(const CPubKey& pubkey) const {
  164. if (pubkey.IsCompressed() != fCompressed) {
  165. return false;
  166. }
  167. unsigned char rnd[8];
  168. std::string str = "Starwels key verification\n";
  169. GetRandBytes(rnd, sizeof(rnd));
  170. uint256 hash;
  171. CHash256().Write((unsigned char*)str.data(), str.size()).Write(rnd, sizeof(rnd)).Finalize(hash.begin());
  172. std::vector<unsigned char> vchSig;
  173. Sign(hash, vchSig);
  174. return pubkey.Verify(hash, vchSig);
  175. }
  176. bool CKey::SignCompact(const uint256 &hash, std::vector<unsigned char>& vchSig) const {
  177. if (!fValid)
  178. return false;
  179. vchSig.resize(65);
  180. int rec = -1;
  181. secp256k1_ecdsa_recoverable_signature sig;
  182. int ret = secp256k1_ecdsa_sign_recoverable(secp256k1_context_sign, &sig, hash.begin(), begin(), secp256k1_nonce_function_rfc6979, nullptr);
  183. assert(ret);
  184. secp256k1_ecdsa_recoverable_signature_serialize_compact(secp256k1_context_sign, (unsigned char*)&vchSig[1], &rec, &sig);
  185. assert(ret);
  186. assert(rec != -1);
  187. vchSig[0] = 27 + rec + (fCompressed ? 4 : 0);
  188. return true;
  189. }
  190. bool CKey::Load(CPrivKey &privkey, CPubKey &vchPubKey, bool fSkipCheck=false) {
  191. if (!ec_privkey_import_der(secp256k1_context_sign, (unsigned char*)begin(), privkey.data(), privkey.size()))
  192. return false;
  193. fCompressed = vchPubKey.IsCompressed();
  194. fValid = true;
  195. if (fSkipCheck)
  196. return true;
  197. return VerifyPubKey(vchPubKey);
  198. }
  199. bool CKey::Derive(CKey& keyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc) const {
  200. assert(IsValid());
  201. assert(IsCompressed());
  202. std::vector<unsigned char, secure_allocator<unsigned char>> vout(64);
  203. if ((nChild >> 31) == 0) {
  204. CPubKey pubkey = GetPubKey();
  205. assert(pubkey.begin() + 33 == pubkey.end());
  206. BIP32Hash(cc, nChild, *pubkey.begin(), pubkey.begin()+1, vout.data());
  207. } else {
  208. assert(begin() + 32 == end());
  209. BIP32Hash(cc, nChild, 0, begin(), vout.data());
  210. }
  211. memcpy(ccChild.begin(), vout.data()+32, 32);
  212. memcpy((unsigned char*)keyChild.begin(), begin(), 32);
  213. bool ret = secp256k1_ec_privkey_tweak_add(secp256k1_context_sign, (unsigned char*)keyChild.begin(), vout.data());
  214. keyChild.fCompressed = true;
  215. keyChild.fValid = ret;
  216. return ret;
  217. }
  218. bool CExtKey::Derive(CExtKey &out, unsigned int _nChild) const {
  219. out.nDepth = nDepth + 1;
  220. CKeyID id = key.GetPubKey().GetID();
  221. memcpy(&out.vchFingerprint[0], &id, 4);
  222. out.nChild = _nChild;
  223. return key.Derive(out.key, out.chaincode, _nChild, chaincode);
  224. }
  225. void CExtKey::SetMaster(const unsigned char *seed, unsigned int nSeedLen) {
  226. static const unsigned char hashkey[] = {'B','i','t','c','o','i','n',' ','s','e','e','d'};
  227. std::vector<unsigned char, secure_allocator<unsigned char>> vout(64);
  228. CHMAC_SHA512(hashkey, sizeof(hashkey)).Write(seed, nSeedLen).Finalize(vout.data());
  229. key.Set(vout.data(), vout.data() + 32, true);
  230. memcpy(chaincode.begin(), vout.data() + 32, 32);
  231. nDepth = 0;
  232. nChild = 0;
  233. memset(vchFingerprint, 0, sizeof(vchFingerprint));
  234. }
  235. CExtPubKey CExtKey::Neuter() const {
  236. CExtPubKey ret;
  237. ret.nDepth = nDepth;
  238. memcpy(&ret.vchFingerprint[0], &vchFingerprint[0], 4);
  239. ret.nChild = nChild;
  240. ret.pubkey = key.GetPubKey();
  241. ret.chaincode = chaincode;
  242. return ret;
  243. }
  244. void CExtKey::Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const {
  245. code[0] = nDepth;
  246. memcpy(code+1, vchFingerprint, 4);
  247. code[5] = (nChild >> 24) & 0xFF; code[6] = (nChild >> 16) & 0xFF;
  248. code[7] = (nChild >> 8) & 0xFF; code[8] = (nChild >> 0) & 0xFF;
  249. memcpy(code+9, chaincode.begin(), 32);
  250. code[41] = 0;
  251. assert(key.size() == 32);
  252. memcpy(code+42, key.begin(), 32);
  253. }
  254. void CExtKey::Decode(const unsigned char code[BIP32_EXTKEY_SIZE]) {
  255. nDepth = code[0];
  256. memcpy(vchFingerprint, code+1, 4);
  257. nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8];
  258. memcpy(chaincode.begin(), code+9, 32);
  259. key.Set(code+42, code+BIP32_EXTKEY_SIZE, true);
  260. }
  261. bool ECC_InitSanityCheck() {
  262. CKey key;
  263. key.MakeNewKey(true);
  264. CPubKey pubkey = key.GetPubKey();
  265. return key.VerifyPubKey(pubkey);
  266. }
  267. void ECC_Start() {
  268. assert(secp256k1_context_sign == nullptr);
  269. secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN);
  270. assert(ctx != nullptr);
  271. {
  272. // Pass in a random blinding seed to the secp256k1 context.
  273. std::vector<unsigned char, secure_allocator<unsigned char>> vseed(32);
  274. GetRandBytes(vseed.data(), 32);
  275. bool ret = secp256k1_context_randomize(ctx, vseed.data());
  276. assert(ret);
  277. }
  278. secp256k1_context_sign = ctx;
  279. }
  280. void ECC_Stop() {
  281. secp256k1_context *ctx = secp256k1_context_sign;
  282. secp256k1_context_sign = nullptr;
  283. if (ctx) {
  284. secp256k1_context_destroy(ctx);
  285. }
  286. }