Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

crypto, refactor: add new KeyPair class #30051

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
71 changes: 50 additions & 21 deletions src/key.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -277,27 +277,7 @@ bool CKey::SignCompact(const uint256 &hash, std::vector<unsigned char>& vchSig)

bool CKey::SignSchnorr(const uint256& hash, Span<unsigned char> sig, const uint256* merkle_root, const uint256& aux) const
{
assert(sig.size() == 64);
secp256k1_keypair keypair;
if (!secp256k1_keypair_create(secp256k1_context_sign, &keypair, UCharCast(begin()))) return false;
if (merkle_root) {
secp256k1_xonly_pubkey pubkey;
if (!secp256k1_keypair_xonly_pub(secp256k1_context_sign, &pubkey, nullptr, &keypair)) return false;
unsigned char pubkey_bytes[32];
if (!secp256k1_xonly_pubkey_serialize(secp256k1_context_sign, pubkey_bytes, &pubkey)) return false;
uint256 tweak = XOnlyPubKey(pubkey_bytes).ComputeTapTweakHash(merkle_root->IsNull() ? nullptr : merkle_root);
if (!secp256k1_keypair_xonly_tweak_add(secp256k1_context_static, &keypair, tweak.data())) return false;
}
bool ret = secp256k1_schnorrsig_sign32(secp256k1_context_sign, sig.data(), hash.data(), &keypair, aux.data());
if (ret) {
// Additional verification step to prevent using a potentially corrupted signature
secp256k1_xonly_pubkey pubkey_verify;
ret = secp256k1_keypair_xonly_pub(secp256k1_context_static, &pubkey_verify, nullptr, &keypair);
ret &= secp256k1_schnorrsig_verify(secp256k1_context_static, sig.data(), hash.begin(), 32, &pubkey_verify);
}
if (!ret) memory_cleanse(sig.data(), sig.size());
memory_cleanse(&keypair, sizeof(keypair));
return ret;
return ComputeKeyPair(merkle_root).SignSchnorr(hash, sig, aux);
}

bool CKey::Load(const CPrivKey &seckey, const CPubKey &vchPubKey, bool fSkipCheck=false) {
Expand Down Expand Up @@ -369,6 +349,11 @@ ECDHSecret CKey::ComputeBIP324ECDHSecret(const EllSwiftPubKey& their_ellswift, c
return output;
}

KeyPair CKey::ComputeKeyPair(const uint256* merkle_root) const
{
return KeyPair(*this, merkle_root);
}

CKey GenerateRandomKey(bool compressed) noexcept
{
CKey key;
Expand Down Expand Up @@ -426,6 +411,50 @@ void CExtKey::Decode(const unsigned char code[BIP32_EXTKEY_SIZE]) {
if ((nDepth == 0 && (nChild != 0 || ReadLE32(vchFingerprint) != 0)) || code[41] != 0) key = CKey();
}

KeyPair::KeyPair(const CKey& key, const uint256* merkle_root)
{
static_assert(std::tuple_size<KeyType>() == sizeof(secp256k1_keypair));
auto keydata = make_secure_unique<KeyType>();
if (!secp256k1_keypair_create(secp256k1_context_sign, reinterpret_cast<secp256k1_keypair*>(keydata->data()), UCharCast(key.data()))) return;
if (merkle_root) {
secp256k1_xonly_pubkey pubkey;
if (!secp256k1_keypair_xonly_pub(secp256k1_context_sign, &pubkey, nullptr, reinterpret_cast<secp256k1_keypair*>(keydata->data()))) return;
unsigned char pubkey_bytes[32];
if (!secp256k1_xonly_pubkey_serialize(secp256k1_context_sign, pubkey_bytes, &pubkey)) return;
uint256 tweak = XOnlyPubKey(pubkey_bytes).ComputeTapTweakHash(merkle_root->IsNull() ? nullptr : merkle_root);
if (!secp256k1_keypair_xonly_tweak_add(secp256k1_context_static, reinterpret_cast<secp256k1_keypair*>(keydata->data()), tweak.data())) return;
}
m_keydata = std::move(keydata);
}

bool KeyPair::GetKey(CKey& key) const
{
if (!m_keydata) return false;
unsigned char tweaked_secret_bytes[32];
if (!secp256k1_keypair_sec(secp256k1_context_sign, tweaked_secret_bytes, reinterpret_cast<secp256k1_keypair*>(m_keydata->data()))) {
return false;
}
key.Set(std::begin(tweaked_secret_bytes), std::end(tweaked_secret_bytes), true);
memory_cleanse(tweaked_secret_bytes, sizeof(tweaked_secret_bytes));
return true;
}

bool KeyPair::SignSchnorr(const uint256& hash, Span<unsigned char> sig, const uint256& aux) const
{
if (!m_keydata) return false;
assert(sig.size() == 64);
bool ret;
ret = secp256k1_schnorrsig_sign32(secp256k1_context_sign, sig.data(), hash.data(), reinterpret_cast<secp256k1_keypair*>(m_keydata->data()), aux.data());
if (ret) {
// Additional verification step to prevent using a potentially corrupted signature
secp256k1_xonly_pubkey pubkey_verify;
ret = secp256k1_keypair_xonly_pub(secp256k1_context_static, &pubkey_verify, nullptr, reinterpret_cast<secp256k1_keypair*>(m_keydata->data()));
ret &= secp256k1_schnorrsig_verify(secp256k1_context_static, sig.data(), hash.begin(), 32, &pubkey_verify);
}
if (!ret) memory_cleanse(sig.data(), sig.size());
return ret;
}

bool ECC_InitSanityCheck() {
CKey key = GenerateRandomKey();
CPubKey pubkey = key.GetPubKey();
Expand Down
51 changes: 51 additions & 0 deletions src/key.h
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ constexpr static size_t ECDH_SECRET_SIZE = CSHA256::OUTPUT_SIZE;
// Used to represent ECDH shared secret (ECDH_SECRET_SIZE bytes)
using ECDHSecret = std::array<std::byte, ECDH_SECRET_SIZE>;

class KeyPair;

/** An encapsulated private key. */
class CKey
{
Expand Down Expand Up @@ -203,6 +205,20 @@ class CKey
ECDHSecret ComputeBIP324ECDHSecret(const EllSwiftPubKey& their_ellswift,
const EllSwiftPubKey& our_ellswift,
bool initiating) const;
/** Compute a KeyPair
*
* Wraps a `secp256k1_keypair` type. `merkle_root` is used to optionally perform tweaking of
* the internal key, as specified in BIP341:
*
* - If merkle_root == nullptr: no tweaking is done, use the internal key directly (this is
* used for signatures in BIP342 script).
* - If merkle_root->IsNull(): tweak the internal key with H_TapTweak(pubkey) (this is used for
* key path spending when no scripts are present).
* - Otherwise: tweak the internal key H_TapTweak(pubkey || *merkle_root)
* (this is used for key path spending, with specific
* Merkle root of the script tree).
*/
KeyPair ComputeKeyPair(const uint256* merkle_root) const;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could use a comment.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

};

CKey GenerateRandomKey(bool compressed = true) noexcept;
Expand Down Expand Up @@ -236,6 +252,41 @@ struct CExtKey {
void SetSeed(Span<const std::byte> seed);
};

/** KeyPair
*
* Wraps a `secp256k1_keypair` type. `merkle_root` is used to optionally perform tweaking of
* the internal key, as specified in BIP341:
*
* - If merkle_root == nullptr: no tweaking is done, use the internal key directly (this is
* used for signatures in BIP342 script).
* - If merkle_root->IsNull(): tweak the internal key with H_TapTweak(pubkey) (this is used for
* key path spending when no scripts are present).
* - Otherwise: tweak the internal key H_TapTweak(pubkey || *merkle_root)
* (this is used for key path spending, with specific
* Merkle root of the script tree).
*/
class KeyPair
{
public:
KeyPair(KeyPair&&) noexcept = default;
KeyPair& operator=(KeyPair&&) noexcept = default;

friend KeyPair CKey::ComputeKeyPair(const uint256* merkle_root) const;
[[nodiscard]] bool GetKey(CKey& key) const;
[[nodiscard]] bool SignSchnorr(const uint256& hash, Span<unsigned char> sig, const uint256& aux) const;

//! Simple read-only vector-like interface.
unsigned int size() const { return m_keydata ? m_keydata->size() : 0; }
const std::byte* data() const { return m_keydata ? reinterpret_cast<const std::byte*>(m_keydata->data()) : nullptr; }
const std::byte* begin() const { return data(); }
const std::byte* end() const { return data() + size(); }
private:
KeyPair(const CKey& key, const uint256* merkle_root);

using KeyType = std::array<unsigned char, 96>;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: would it make sense to extract the 96 to a const?

constexpr size_t SECP256K1_KEYPAIR_SIZE = 96;
using KeyType = std::array<unsigned char, SECP256K1_KEYPAIR_SIZE>;

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't really see a benefit. We shouldn't be exposing this value to anything outside the class, so defining a constexpr here seems unnecessarily verbose.

secure_unique_ptr<KeyType> m_keydata;
};

/** Check that required EC support is available at runtime. */
bool ECC_InitSanityCheck();

Expand Down
20 changes: 20 additions & 0 deletions src/test/key_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,16 @@ BOOST_AUTO_TEST_CASE(bip340_test_vectors)
// Verify those signatures for good measure.
BOOST_CHECK(pubkey.VerifySchnorr(msg256, sig64));

// Repeat the same check, but use the KeyPair directly without any merkle tweak
KeyPair keypair = key.ComputeKeyPair(/*merkle_root=*/nullptr);
CKey keypair_seckey;
BOOST_CHECK(keypair.GetKey(keypair_seckey));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: BOOST_CHECK_MESSAGE often produces more readable results, but it may be inconvenient to set it up properly. If you think it adds value, it may be helpful to add some debug info as a message in case of likely failures.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think it adds much here? We are using BOOST_CHECK to to ensure the function call succeeds before proceeding, so getting a line number failure for BOOST_CHECK seems sufficient for debugging. Also, if dealing with valid keys, this function should never fail.

BOOST_CHECK(key == keypair_seckey);
bool kp_ok = keypair.SignSchnorr(msg256, sig64, aux256);
BOOST_CHECK(kp_ok);
XOnlyPubKey keypair_xonly{keypair_seckey.GetPubKey()};
BOOST_CHECK(keypair_xonly.VerifySchnorr(msg256, sig64));

// Do 10 iterations where we sign with a random Merkle root to tweak,
// and compare against the resulting tweaked keys, with random aux.
// In iteration i=0 we tweak with empty Merkle tree.
Expand All @@ -340,6 +350,16 @@ BOOST_AUTO_TEST_CASE(bip340_test_vectors)
bool ok = key.SignSchnorr(msg256, sig64, &merkle_root, aux256);
BOOST_CHECK(ok);
BOOST_CHECK(tweaked_key.VerifySchnorr(msg256, sig64));

// Repeat the same check, but use the KeyPair class directly
KeyPair keypair = key.ComputeKeyPair(&merkle_root);
CKey keypair_seckey;
BOOST_CHECK(keypair.GetKey(keypair_seckey));
XOnlyPubKey keypair_xonly{keypair_seckey.GetPubKey()};
BOOST_CHECK(tweaked_key == keypair_xonly);
bool kp_ok = keypair.SignSchnorr(msg256, sig64, aux256);
BOOST_CHECK(kp_ok);
BOOST_CHECK(keypair_xonly.VerifySchnorr(msg256, sig64));
}
}
}
Expand Down