I'm working on a project that utilizes this library to generate an ecc public key based on a private key. It's very likely I am misunderstanding how to use this library and/or c++, but I was looking for a reference example of a unit test to verify that the generated public key is correct. Maybe someone can point me in the right direction. Here's what I'm trying to do, but it doesn't seem to be generating the correct public key:
BOOST_AUTO_TEST_CASE(test_importprivkey)
{
KeyPair keypair;
unsigned char priv_key[KeyPair::PRIVATE_KEY_SIZE_BYTES] = {0x18,0xE1,0x4A,0x7B,0x6A,0x30,0x7F,0x42,0x6A,0x94,0xF8,0x11,0x47,0x01,0xE7,0xC8,0xE7,0x74,0xE7,0xF9,0xA4,0x7E,0x2C,0x20,0x35,0xDB,0x29,0xA2,0x06,0x32,0x17,0x25};
unsigned char expected_pub_key[KeyPair::PUBLIC_KEY_SIZE_BYTES] = {0x04,0x50,0x86,0x3A,0xD6,0x4A,0x87,0xAE,0x8A,0x2F,0xE8,0x3C,0x1A,0xF1,0xA8,0x40,0x3C,0xB5,0x3F,0x53,0xE4,0x86,0xD8,0x51,0x1D,0xAD,0x8A,0x04,0x88,0x7E,0x5B,0x23,0x52,0x2C,0xD4,0x70,0x24,0x34,0x53,0xA2,0x99,0xFA,0x9E,0x77,0x23,0x77,0x16,0x10,0x3A,0xBC,0x11,0xA1,0xDF,0x38,0x85,0x5E,0xD6,0xF2,0xEE,0x18,0x7E,0x9C,0x58,0x2B,0xA6};
keypair.ImportPrivKey(priv_key);
BOOST_ASSERT(memcmp(expected_pub_key, &keypair.pub_key, KeyPair::PUBLIC_KEY_SIZE_BYTES) == 0);
}
My source code:
void KeyPair::ImportPrivKey(const unsigned char priv_key[KeyPair::PUBLIC_KEY_SIZE_BYTES])
{
// TODO: pass this in as a parameter
bool fCompressed = false;
// TODO: validate the private key: any 256-bit number from 0x1 to 0xFFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFE BAAE DCE6 AF48 A03B BFD2 5E8C D036 4140 is a valid private key
secp256k1_context* ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN);
secp256k1_pubkey pubkey;
// TODO: change member variable pub_key to be type secp256k1_pubkey and use that in the next function call
int result = secp256k1_ec_pubkey_create(ctx, &pubkey, priv_key);
unsigned char pubkey_buffer;
size_t clen = KeyPair::PUBLIC_KEY_SIZE_BYTES;
secp256k1_ec_pubkey_serialize(ctx, &pubkey_buffer, &clen, &pubkey, fCompressed ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED);
if(result != 0)
{
std::cerr << "Error in ImportPrivKey" << std::endl;
}
}
#ifndef KEY_PAIR_H
#define KEY_PAIR_H
class KeyPair
{
public:
static const unsigned int PRIVATE_KEY_SIZE_BYTES = 32;
static const unsigned int PUBLIC_KEY_SIZE_BYTES = 65;
static const unsigned int PUBLIC_KEY_COMPRESSED_SIZE_BYTES = 33;
unsigned char priv_key[PRIVATE_KEY_SIZE_BYTES];
unsigned char pub_key[PUBLIC_KEY_SIZE_BYTES];
void ImportPrivKey(const unsigned char priv_key[PRIVATE_KEY_SIZE_BYTES]);
};
#endif //KEY_PAIR_H