Skip to content

Commit

Permalink
refactor: move SignSchnorr logic to KeyPair
Browse files Browse the repository at this point in the history
Move `SignSchnorr` to `KeyPair`. This makes `CKey::SignSchnorr` now
compute a `KeyPair` object and then call `KeyPair::SignSchorr`. The
signing logic is move-only with the exception of changing
`keypair.data()` to `my_keypair->data()`, since we now have access to
the private member `m_keypair`.
  • Loading branch information
josibake committed Jul 22, 2024
1 parent f908a30 commit 515d455
Showing 1 changed file with 16 additions and 12 deletions.
28 changes: 16 additions & 12 deletions src/key.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -271,19 +271,8 @@ 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);
KeyPair kp = ComputeKeyPair(merkle_root);
if (!kp.IsValid()) return false;
auto keypair = reinterpret_cast<const secp256k1_keypair*>(kp.data());
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());
return ret;
return kp.IsValid() && kp.SignSchnorr(hash, sig, aux);
}

bool CKey::Load(const CPrivKey &seckey, const CPubKey &vchPubKey, bool fSkipCheck=false) {
Expand Down Expand Up @@ -431,6 +420,21 @@ KeyPair::KeyPair(const CKey& key, const uint256* merkle_root)
if (!success) ClearKeyPairData();
}

bool KeyPair::SignSchnorr(const uint256& hash, Span<unsigned char> sig, const uint256& aux) const
{
assert(sig.size() == 64);
auto keypair = reinterpret_cast<const secp256k1_keypair*>(m_keypair->data());
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());
return ret;
}

bool ECC_InitSanityCheck() {
CKey key = GenerateRandomKey();
CPubKey pubkey = key.GetPubKey();
Expand Down

0 comments on commit 515d455

Please sign in to comment.