Merge #12062: Increment MIT Licence copyright header year on files modified in 2017
[bitcoinplatinum.git] / src / key.cpp
blobf8136f88b5cae129893a659f93729eb64472c7b9
1 // Copyright (c) 2009-2017 The Bitcoin Core developers
2 // Copyright (c) 2017 The Zcash developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #include <key.h>
8 #include <arith_uint256.h>
9 #include <crypto/common.h>
10 #include <crypto/hmac_sha512.h>
11 #include <random.h>
13 #include <secp256k1.h>
14 #include <secp256k1_recovery.h>
16 static secp256k1_context* secp256k1_context_sign = nullptr;
18 /** These functions are taken from the libsecp256k1 distribution and are very ugly. */
20 /**
21 * This parses a format loosely based on a DER encoding of the ECPrivateKey type from
22 * section C.4 of SEC 1 <http://www.secg.org/sec1-v2.pdf>, with the following caveats:
24 * * The octet-length of the SEQUENCE must be encoded as 1 or 2 octets. It is not
25 * required to be encoded as one octet if it is less than 256, as DER would require.
26 * * The octet-length of the SEQUENCE must not be greater than the remaining
27 * length of the key encoding, but need not match it (i.e. the encoding may contain
28 * junk after the encoded SEQUENCE).
29 * * The privateKey OCTET STRING is zero-filled on the left to 32 octets.
30 * * Anything after the encoding of the privateKey OCTET STRING is ignored, whether
31 * or not it is validly encoded DER.
33 * out32 must point to an output buffer of length at least 32 bytes.
35 static int ec_privkey_import_der(const secp256k1_context* ctx, unsigned char *out32, const unsigned char *privkey, size_t privkeylen) {
36 const unsigned char *end = privkey + privkeylen;
37 memset(out32, 0, 32);
38 /* sequence header */
39 if (end - privkey < 1 || *privkey != 0x30u) {
40 return 0;
42 privkey++;
43 /* sequence length constructor */
44 if (end - privkey < 1 || !(*privkey & 0x80u)) {
45 return 0;
47 size_t lenb = *privkey & ~0x80u; privkey++;
48 if (lenb < 1 || lenb > 2) {
49 return 0;
51 if (end - privkey < lenb) {
52 return 0;
54 /* sequence length */
55 size_t len = privkey[lenb-1] | (lenb > 1 ? privkey[lenb-2] << 8 : 0u);
56 privkey += lenb;
57 if (end - privkey < len) {
58 return 0;
60 /* sequence element 0: version number (=1) */
61 if (end - privkey < 3 || privkey[0] != 0x02u || privkey[1] != 0x01u || privkey[2] != 0x01u) {
62 return 0;
64 privkey += 3;
65 /* sequence element 1: octet string, up to 32 bytes */
66 if (end - privkey < 2 || privkey[0] != 0x04u) {
67 return 0;
69 size_t oslen = privkey[1];
70 privkey += 2;
71 if (oslen > 32 || end - privkey < oslen) {
72 return 0;
74 memcpy(out32 + (32 - oslen), privkey, oslen);
75 if (!secp256k1_ec_seckey_verify(ctx, out32)) {
76 memset(out32, 0, 32);
77 return 0;
79 return 1;
82 /**
83 * This serializes to a DER encoding of the ECPrivateKey type from section C.4 of SEC 1
84 * <http://www.secg.org/sec1-v2.pdf>. The optional parameters and publicKey fields are
85 * included.
87 * privkey must point to an output buffer of length at least CKey::PRIVATE_KEY_SIZE bytes.
88 * privkeylen must initially be set to the size of the privkey buffer. Upon return it
89 * will be set to the number of bytes used in the buffer.
90 * key32 must point to a 32-byte raw private key.
92 static int ec_privkey_export_der(const secp256k1_context *ctx, unsigned char *privkey, size_t *privkeylen, const unsigned char *key32, int compressed) {
93 assert(*privkeylen >= CKey::PRIVATE_KEY_SIZE);
94 secp256k1_pubkey pubkey;
95 size_t pubkeylen = 0;
96 if (!secp256k1_ec_pubkey_create(ctx, &pubkey, key32)) {
97 *privkeylen = 0;
98 return 0;
100 if (compressed) {
101 static const unsigned char begin[] = {
102 0x30,0x81,0xD3,0x02,0x01,0x01,0x04,0x20
104 static const unsigned char middle[] = {
105 0xA0,0x81,0x85,0x30,0x81,0x82,0x02,0x01,0x01,0x30,0x2C,0x06,0x07,0x2A,0x86,0x48,
106 0xCE,0x3D,0x01,0x01,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
107 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
108 0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F,0x30,0x06,0x04,0x01,0x00,0x04,0x01,0x07,0x04,
109 0x21,0x02,0x79,0xBE,0x66,0x7E,0xF9,0xDC,0xBB,0xAC,0x55,0xA0,0x62,0x95,0xCE,0x87,
110 0x0B,0x07,0x02,0x9B,0xFC,0xDB,0x2D,0xCE,0x28,0xD9,0x59,0xF2,0x81,0x5B,0x16,0xF8,
111 0x17,0x98,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
112 0xFF,0xFF,0xFF,0xFF,0xFE,0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,0xBF,0xD2,0x5E,
113 0x8C,0xD0,0x36,0x41,0x41,0x02,0x01,0x01,0xA1,0x24,0x03,0x22,0x00
115 unsigned char *ptr = privkey;
116 memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin);
117 memcpy(ptr, key32, 32); ptr += 32;
118 memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle);
119 pubkeylen = CPubKey::COMPRESSED_PUBLIC_KEY_SIZE;
120 secp256k1_ec_pubkey_serialize(ctx, ptr, &pubkeylen, &pubkey, SECP256K1_EC_COMPRESSED);
121 ptr += pubkeylen;
122 *privkeylen = ptr - privkey;
123 assert(*privkeylen == CKey::COMPRESSED_PRIVATE_KEY_SIZE);
124 } else {
125 static const unsigned char begin[] = {
126 0x30,0x82,0x01,0x13,0x02,0x01,0x01,0x04,0x20
128 static const unsigned char middle[] = {
129 0xA0,0x81,0xA5,0x30,0x81,0xA2,0x02,0x01,0x01,0x30,0x2C,0x06,0x07,0x2A,0x86,0x48,
130 0xCE,0x3D,0x01,0x01,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
131 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
132 0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F,0x30,0x06,0x04,0x01,0x00,0x04,0x01,0x07,0x04,
133 0x41,0x04,0x79,0xBE,0x66,0x7E,0xF9,0xDC,0xBB,0xAC,0x55,0xA0,0x62,0x95,0xCE,0x87,
134 0x0B,0x07,0x02,0x9B,0xFC,0xDB,0x2D,0xCE,0x28,0xD9,0x59,0xF2,0x81,0x5B,0x16,0xF8,
135 0x17,0x98,0x48,0x3A,0xDA,0x77,0x26,0xA3,0xC4,0x65,0x5D,0xA4,0xFB,0xFC,0x0E,0x11,
136 0x08,0xA8,0xFD,0x17,0xB4,0x48,0xA6,0x85,0x54,0x19,0x9C,0x47,0xD0,0x8F,0xFB,0x10,
137 0xD4,0xB8,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
138 0xFF,0xFF,0xFF,0xFF,0xFE,0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,0xBF,0xD2,0x5E,
139 0x8C,0xD0,0x36,0x41,0x41,0x02,0x01,0x01,0xA1,0x44,0x03,0x42,0x00
141 unsigned char *ptr = privkey;
142 memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin);
143 memcpy(ptr, key32, 32); ptr += 32;
144 memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle);
145 pubkeylen = CPubKey::PUBLIC_KEY_SIZE;
146 secp256k1_ec_pubkey_serialize(ctx, ptr, &pubkeylen, &pubkey, SECP256K1_EC_UNCOMPRESSED);
147 ptr += pubkeylen;
148 *privkeylen = ptr - privkey;
149 assert(*privkeylen == CKey::PRIVATE_KEY_SIZE);
151 return 1;
154 bool CKey::Check(const unsigned char *vch) {
155 return secp256k1_ec_seckey_verify(secp256k1_context_sign, vch);
158 void CKey::MakeNewKey(bool fCompressedIn) {
159 do {
160 GetStrongRandBytes(keydata.data(), keydata.size());
161 } while (!Check(keydata.data()));
162 fValid = true;
163 fCompressed = fCompressedIn;
166 CPrivKey CKey::GetPrivKey() const {
167 assert(fValid);
168 CPrivKey privkey;
169 int ret;
170 size_t privkeylen;
171 privkey.resize(PRIVATE_KEY_SIZE);
172 privkeylen = PRIVATE_KEY_SIZE;
173 ret = ec_privkey_export_der(secp256k1_context_sign, (unsigned char*) privkey.data(), &privkeylen, begin(), fCompressed ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED);
174 assert(ret);
175 privkey.resize(privkeylen);
176 return privkey;
179 CPubKey CKey::GetPubKey() const {
180 assert(fValid);
181 secp256k1_pubkey pubkey;
182 size_t clen = CPubKey::PUBLIC_KEY_SIZE;
183 CPubKey result;
184 int ret = secp256k1_ec_pubkey_create(secp256k1_context_sign, &pubkey, begin());
185 assert(ret);
186 secp256k1_ec_pubkey_serialize(secp256k1_context_sign, (unsigned char*)result.begin(), &clen, &pubkey, fCompressed ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED);
187 assert(result.size() == clen);
188 assert(result.IsValid());
189 return result;
192 bool CKey::Sign(const uint256 &hash, std::vector<unsigned char>& vchSig, uint32_t test_case) const {
193 if (!fValid)
194 return false;
195 vchSig.resize(CPubKey::SIGNATURE_SIZE);
196 size_t nSigLen = CPubKey::SIGNATURE_SIZE;
197 unsigned char extra_entropy[32] = {0};
198 WriteLE32(extra_entropy, test_case);
199 secp256k1_ecdsa_signature sig;
200 int ret = secp256k1_ecdsa_sign(secp256k1_context_sign, &sig, hash.begin(), begin(), secp256k1_nonce_function_rfc6979, test_case ? extra_entropy : nullptr);
201 assert(ret);
202 secp256k1_ecdsa_signature_serialize_der(secp256k1_context_sign, (unsigned char*)vchSig.data(), &nSigLen, &sig);
203 vchSig.resize(nSigLen);
204 return true;
207 bool CKey::VerifyPubKey(const CPubKey& pubkey) const {
208 if (pubkey.IsCompressed() != fCompressed) {
209 return false;
211 unsigned char rnd[8];
212 std::string str = "Bitcoin key verification\n";
213 GetRandBytes(rnd, sizeof(rnd));
214 uint256 hash;
215 CHash256().Write((unsigned char*)str.data(), str.size()).Write(rnd, sizeof(rnd)).Finalize(hash.begin());
216 std::vector<unsigned char> vchSig;
217 Sign(hash, vchSig);
218 return pubkey.Verify(hash, vchSig);
221 bool CKey::SignCompact(const uint256 &hash, std::vector<unsigned char>& vchSig) const {
222 if (!fValid)
223 return false;
224 vchSig.resize(CPubKey::COMPACT_SIGNATURE_SIZE);
225 int rec = -1;
226 secp256k1_ecdsa_recoverable_signature sig;
227 int ret = secp256k1_ecdsa_sign_recoverable(secp256k1_context_sign, &sig, hash.begin(), begin(), secp256k1_nonce_function_rfc6979, nullptr);
228 assert(ret);
229 secp256k1_ecdsa_recoverable_signature_serialize_compact(secp256k1_context_sign, (unsigned char*)&vchSig[1], &rec, &sig);
230 assert(ret);
231 assert(rec != -1);
232 vchSig[0] = 27 + rec + (fCompressed ? 4 : 0);
233 return true;
236 bool CKey::Load(CPrivKey &privkey, CPubKey &vchPubKey, bool fSkipCheck=false) {
237 if (!ec_privkey_import_der(secp256k1_context_sign, (unsigned char*)begin(), privkey.data(), privkey.size()))
238 return false;
239 fCompressed = vchPubKey.IsCompressed();
240 fValid = true;
242 if (fSkipCheck)
243 return true;
245 return VerifyPubKey(vchPubKey);
248 bool CKey::Derive(CKey& keyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc) const {
249 assert(IsValid());
250 assert(IsCompressed());
251 std::vector<unsigned char, secure_allocator<unsigned char>> vout(64);
252 if ((nChild >> 31) == 0) {
253 CPubKey pubkey = GetPubKey();
254 assert(pubkey.size() == CPubKey::COMPRESSED_PUBLIC_KEY_SIZE);
255 BIP32Hash(cc, nChild, *pubkey.begin(), pubkey.begin()+1, vout.data());
256 } else {
257 assert(size() == 32);
258 BIP32Hash(cc, nChild, 0, begin(), vout.data());
260 memcpy(ccChild.begin(), vout.data()+32, 32);
261 memcpy((unsigned char*)keyChild.begin(), begin(), 32);
262 bool ret = secp256k1_ec_privkey_tweak_add(secp256k1_context_sign, (unsigned char*)keyChild.begin(), vout.data());
263 keyChild.fCompressed = true;
264 keyChild.fValid = ret;
265 return ret;
268 bool CExtKey::Derive(CExtKey &out, unsigned int _nChild) const {
269 out.nDepth = nDepth + 1;
270 CKeyID id = key.GetPubKey().GetID();
271 memcpy(&out.vchFingerprint[0], &id, 4);
272 out.nChild = _nChild;
273 return key.Derive(out.key, out.chaincode, _nChild, chaincode);
276 void CExtKey::SetMaster(const unsigned char *seed, unsigned int nSeedLen) {
277 static const unsigned char hashkey[] = {'B','i','t','c','o','i','n',' ','s','e','e','d'};
278 std::vector<unsigned char, secure_allocator<unsigned char>> vout(64);
279 CHMAC_SHA512(hashkey, sizeof(hashkey)).Write(seed, nSeedLen).Finalize(vout.data());
280 key.Set(vout.data(), vout.data() + 32, true);
281 memcpy(chaincode.begin(), vout.data() + 32, 32);
282 nDepth = 0;
283 nChild = 0;
284 memset(vchFingerprint, 0, sizeof(vchFingerprint));
287 CExtPubKey CExtKey::Neuter() const {
288 CExtPubKey ret;
289 ret.nDepth = nDepth;
290 memcpy(&ret.vchFingerprint[0], &vchFingerprint[0], 4);
291 ret.nChild = nChild;
292 ret.pubkey = key.GetPubKey();
293 ret.chaincode = chaincode;
294 return ret;
297 void CExtKey::Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const {
298 code[0] = nDepth;
299 memcpy(code+1, vchFingerprint, 4);
300 code[5] = (nChild >> 24) & 0xFF; code[6] = (nChild >> 16) & 0xFF;
301 code[7] = (nChild >> 8) & 0xFF; code[8] = (nChild >> 0) & 0xFF;
302 memcpy(code+9, chaincode.begin(), 32);
303 code[41] = 0;
304 assert(key.size() == 32);
305 memcpy(code+42, key.begin(), 32);
308 void CExtKey::Decode(const unsigned char code[BIP32_EXTKEY_SIZE]) {
309 nDepth = code[0];
310 memcpy(vchFingerprint, code+1, 4);
311 nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8];
312 memcpy(chaincode.begin(), code+9, 32);
313 key.Set(code+42, code+BIP32_EXTKEY_SIZE, true);
316 bool ECC_InitSanityCheck() {
317 CKey key;
318 key.MakeNewKey(true);
319 CPubKey pubkey = key.GetPubKey();
320 return key.VerifyPubKey(pubkey);
323 void ECC_Start() {
324 assert(secp256k1_context_sign == nullptr);
326 secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN);
327 assert(ctx != nullptr);
330 // Pass in a random blinding seed to the secp256k1 context.
331 std::vector<unsigned char, secure_allocator<unsigned char>> vseed(32);
332 GetRandBytes(vseed.data(), 32);
333 bool ret = secp256k1_context_randomize(ctx, vseed.data());
334 assert(ret);
337 secp256k1_context_sign = ctx;
340 void ECC_Stop() {
341 secp256k1_context *ctx = secp256k1_context_sign;
342 secp256k1_context_sign = nullptr;
344 if (ctx) {
345 secp256k1_context_destroy(ctx);