Inside Bitcoin
Opening the selected file…
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) 2009-present The Bitcoin Core developers2// Copyright (c) 2017 The Zcash developers3// Distributed under the MIT software license, see the accompanying4// file COPYING or http://www.opensource.org/licenses/mit-license.php.6#include <key.h>8#include <crypto/common.h>9#include <crypto/hmac_sha512.h>10#include <hash.h>11#include <random.h>13#include <secp256k1.h>14#include <secp256k1_ellswift.h>15#include <secp256k1_extrakeys.h>16#include <secp256k1_recovery.h>17#include <secp256k1_schnorrsig.h>19#include <algorithm>21static secp256k1_context* secp256k1_context_sign = nullptr;23/** These functions are taken from the libsecp256k1 distribution and are very ugly. */25/**26* This parses a format loosely based on a DER encoding of the ECPrivateKey type from27* section C.4 of SEC 1 <https://www.secg.org/sec1-v2.pdf>, with the following caveats:28*29* * The octet-length of the SEQUENCE must be encoded as 1 or 2 octets. It is not30* required to be encoded as one octet if it is less than 256, as DER would require.31* * The octet-length of the SEQUENCE must not be greater than the remaining32* length of the key encoding, but need not match it (i.e. the encoding may contain33* junk after the encoded SEQUENCE).34* * The privateKey OCTET STRING is zero-filled on the left to 32 octets.35* * Anything after the encoding of the privateKey OCTET STRING is ignored, whether36* or not it is validly encoded DER.37*38* out32 must point to an output buffer of length at least 32 bytes.39*/40int ec_seckey_import_der(const secp256k1_context* ctx, unsigned char *out32, const unsigned char *seckey, size_t seckeylen) {41const unsigned char *end = seckey + seckeylen;42memset(out32, 0, 32);43/* sequence header */44if (end - seckey < 1 || *seckey != 0x30u) {45return 0;46}47seckey++;48/* sequence length constructor */49if (end - seckey < 1 || !(*seckey & 0x80u)) {50return 0;51}52ptrdiff_t lenb = *seckey & ~0x80u; seckey++;53if (lenb < 1 || lenb > 2) {54return 0;55}56if (end - seckey < lenb) {57return 0;58}59/* sequence length */60ptrdiff_t len = seckey[lenb-1] | (lenb > 1 ? seckey[lenb-2] << 8 : 0u);61seckey += lenb;62if (end - seckey < len) {63return 0;64}65/* sequence element 0: version number (=1) */66if (end - seckey < 3 || seckey[0] != 0x02u || seckey[1] != 0x01u || seckey[2] != 0x01u) {67return 0;68}69seckey += 3;70/* sequence element 1: octet string, up to 32 bytes */71if (end - seckey < 2 || seckey[0] != 0x04u) {72return 0;73}74ptrdiff_t oslen = seckey[1];75seckey += 2;76if (oslen > 32 || end - seckey < oslen) {77return 0;78}79memcpy(out32 + (32 - oslen), seckey, oslen);80if (!secp256k1_ec_seckey_verify(ctx, out32)) {81memset(out32, 0, 32);82return 0;83}84return 1;85}87/**88* This serializes to a DER encoding of the ECPrivateKey type from section C.4 of SEC 189* <https://www.secg.org/sec1-v2.pdf>. The optional parameters and publicKey fields are90* included.91*92* seckey must point to an output buffer of length at least CKey::SIZE bytes.93* seckeylen must initially be set to the size of the seckey buffer. Upon return it94* will be set to the number of bytes used in the buffer.95* key32 must point to a 32-byte raw private key.96*/97int ec_seckey_export_der(const secp256k1_context *ctx, unsigned char *seckey, size_t *seckeylen, const unsigned char *key32, bool compressed) {98assert(*seckeylen >= CKey::SIZE);99secp256k1_pubkey pubkey;100size_t pubkeylen = 0;101if (!secp256k1_ec_pubkey_create(ctx, &pubkey, key32)) {102*seckeylen = 0;103return 0;104}105if (compressed) {106static const unsigned char begin[] = {1070x30,0x81,0xD3,0x02,0x01,0x01,0x04,0x20108};109static const unsigned char middle[] = {1100xA0,0x81,0x85,0x30,0x81,0x82,0x02,0x01,0x01,0x30,0x2C,0x06,0x07,0x2A,0x86,0x48,1110xCE,0x3D,0x01,0x01,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,1120xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,1130xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F,0x30,0x06,0x04,0x01,0x00,0x04,0x01,0x07,0x04,1140x21,0x02,0x79,0xBE,0x66,0x7E,0xF9,0xDC,0xBB,0xAC,0x55,0xA0,0x62,0x95,0xCE,0x87,1150x0B,0x07,0x02,0x9B,0xFC,0xDB,0x2D,0xCE,0x28,0xD9,0x59,0xF2,0x81,0x5B,0x16,0xF8,1160x17,0x98,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,1170xFF,0xFF,0xFF,0xFF,0xFE,0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,0xBF,0xD2,0x5E,1180x8C,0xD0,0x36,0x41,0x41,0x02,0x01,0x01,0xA1,0x24,0x03,0x22,0x00119};120unsigned char *ptr = seckey;121memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin);122memcpy(ptr, key32, 32); ptr += 32;123memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle);124pubkeylen = CPubKey::COMPRESSED_SIZE;125secp256k1_ec_pubkey_serialize(ctx, ptr, &pubkeylen, &pubkey, SECP256K1_EC_COMPRESSED);126ptr += pubkeylen;127*seckeylen = ptr - seckey;128assert(*seckeylen == CKey::COMPRESSED_SIZE);129} else {130static const unsigned char begin[] = {1310x30,0x82,0x01,0x13,0x02,0x01,0x01,0x04,0x20132};133static const unsigned char middle[] = {1340xA0,0x81,0xA5,0x30,0x81,0xA2,0x02,0x01,0x01,0x30,0x2C,0x06,0x07,0x2A,0x86,0x48,1350xCE,0x3D,0x01,0x01,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,1360xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,1370xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F,0x30,0x06,0x04,0x01,0x00,0x04,0x01,0x07,0x04,1380x41,0x04,0x79,0xBE,0x66,0x7E,0xF9,0xDC,0xBB,0xAC,0x55,0xA0,0x62,0x95,0xCE,0x87,1390x0B,0x07,0x02,0x9B,0xFC,0xDB,0x2D,0xCE,0x28,0xD9,0x59,0xF2,0x81,0x5B,0x16,0xF8,1400x17,0x98,0x48,0x3A,0xDA,0x77,0x26,0xA3,0xC4,0x65,0x5D,0xA4,0xFB,0xFC,0x0E,0x11,1410x08,0xA8,0xFD,0x17,0xB4,0x48,0xA6,0x85,0x54,0x19,0x9C,0x47,0xD0,0x8F,0xFB,0x10,1420xD4,0xB8,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,1430xFF,0xFF,0xFF,0xFF,0xFE,0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,0xBF,0xD2,0x5E,1440x8C,0xD0,0x36,0x41,0x41,0x02,0x01,0x01,0xA1,0x44,0x03,0x42,0x00145};146unsigned char *ptr = seckey;147memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin);148memcpy(ptr, key32, 32); ptr += 32;149memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle);150pubkeylen = CPubKey::SIZE;151secp256k1_ec_pubkey_serialize(ctx, ptr, &pubkeylen, &pubkey, SECP256K1_EC_UNCOMPRESSED);152ptr += pubkeylen;153*seckeylen = ptr - seckey;154assert(*seckeylen == CKey::SIZE);155}156return 1;157}159bool CKey::Check(const unsigned char *vch) {160return secp256k1_ec_seckey_verify(secp256k1_context_static, vch);161}163void CKey::MakeNewKey(bool fCompressedIn) {164MakeKeyData();165do {166GetStrongRandBytes(*keydata);167} while (!Check(keydata->data()));168fCompressed = fCompressedIn;169}171CPrivKey CKey::GetPrivKey() const {172assert(keydata);173CPrivKey seckey;174int ret;175size_t seckeylen;176seckey.resize(SIZE);177seckeylen = SIZE;178ret = ec_seckey_export_der(secp256k1_context_sign, seckey.data(), &seckeylen, UCharCast(begin()), fCompressed);179assert(ret);180seckey.resize(seckeylen);181return seckey;182}184CPubKey CKey::GetPubKey() const {185assert(keydata);186secp256k1_pubkey pubkey;187size_t clen = CPubKey::SIZE;188CPubKey result;189int ret = secp256k1_ec_pubkey_create(secp256k1_context_sign, &pubkey, UCharCast(begin()));190assert(ret);191secp256k1_ec_pubkey_serialize(secp256k1_context_static, (unsigned char*)result.begin(), &clen, &pubkey, fCompressed ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED);192assert(result.size() == clen);193assert(result.IsValid());194return result;195}197// Check that the sig has a low R value and will be less than 71 bytes198bool SigHasLowR(const secp256k1_ecdsa_signature* sig)199{200unsigned char compact_sig[64];201secp256k1_ecdsa_signature_serialize_compact(secp256k1_context_static, compact_sig, sig);203// In DER serialization, all values are interpreted as big-endian, signed integers. The highest bit in the integer indicates204// its signed-ness; 0 is positive, 1 is negative. When the value is interpreted as a negative integer, it must be converted205// to a positive value by prepending a 0x00 byte so that the highest bit is 0. We can avoid this prepending by ensuring that206// our highest bit is always 0, and thus we must check that the first byte is less than 0x80.207return compact_sig[0] < 0x80;208}210bool CKey::Sign(const uint256 &hash, std::vector<unsigned char>& vchSig, bool grind, uint32_t test_case) const {211if (!keydata)212return false;213vchSig.resize(CPubKey::SIGNATURE_SIZE);214size_t nSigLen = CPubKey::SIGNATURE_SIZE;215unsigned char extra_entropy[32] = {0};216WriteLE32(extra_entropy, test_case);217secp256k1_ecdsa_signature sig;218uint32_t counter = 0;219int ret = secp256k1_ecdsa_sign(secp256k1_context_sign, &sig, hash.begin(), UCharCast(begin()), secp256k1_nonce_function_rfc6979, (!grind && test_case) ? extra_entropy : nullptr);221// Grind for low R222while (ret && !SigHasLowR(&sig) && grind) {223WriteLE32(extra_entropy, ++counter);224ret = secp256k1_ecdsa_sign(secp256k1_context_sign, &sig, hash.begin(), UCharCast(begin()), secp256k1_nonce_function_rfc6979, extra_entropy);225}226assert(ret);227secp256k1_ecdsa_signature_serialize_der(secp256k1_context_static, vchSig.data(), &nSigLen, &sig);228vchSig.resize(nSigLen);229// Additional verification step to prevent using a potentially corrupted signature230secp256k1_pubkey pk;231ret = secp256k1_ec_pubkey_create(secp256k1_context_sign, &pk, UCharCast(begin()));232assert(ret);233ret = secp256k1_ecdsa_verify(secp256k1_context_static, &sig, hash.begin(), &pk);234assert(ret);235return true;236}238bool CKey::VerifyPubKey(const CPubKey& pubkey) const {239if (pubkey.IsCompressed() != fCompressed) {240return false;241}242unsigned char rnd[8];243std::string str = "Bitcoin key verification\n";244GetRandBytes(rnd);245uint256 hash{Hash(str, rnd)};246std::vector<unsigned char> vchSig;247Sign(hash, vchSig);248return pubkey.Verify(hash, vchSig);249}
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.