Skip to content

Commit

Permalink
CKey: add Serialize and Unserialize
Browse files Browse the repository at this point in the history
Co-authored-by: Vasil Dimov <[email protected]>
  • Loading branch information
Sjors and vasild committed Dec 19, 2024
1 parent f8ebcbb commit ef523cd
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/key.h
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,7 @@ class CKey
ECDHSecret ComputeBIP324ECDHSecret(const EllSwiftPubKey& their_ellswift,
const EllSwiftPubKey& our_ellswift,
bool initiating) const;

/** Compute a KeyPair
*
* Wraps a `secp256k1_keypair` type.
Expand All @@ -220,6 +221,31 @@ class CKey
* Merkle root of the script tree).
*/
KeyPair ComputeKeyPair(const uint256* merkle_root) const;

/** Straight-forward serialization of key bytes (and compressed flag).
* Use GetPrivKey() for OpenSSL compatible DER encoding.
*/
template <typename Stream>
void Serialize(Stream& s) const
{
if (!IsValid()) {
throw std::ios_base::failure("invalid key");
}
s << fCompressed;
::Serialize(s, Span{*this});
}

template <typename Stream>
void Unserialize(Stream& s)
{
s >> fCompressed;
MakeKeyData();
s >> Span{*keydata};
if (!Check(keydata->data())) {
ClearKeyData();
throw std::ios_base::failure("invalid key");
}
}
};

CKey GenerateRandomKey(bool compressed = true) noexcept;
Expand Down
23 changes: 23 additions & 0 deletions src/test/key_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -390,4 +390,27 @@ BOOST_AUTO_TEST_CASE(key_schnorr_tweak_smoke_test)
secp256k1_context_destroy(secp256k1_context_sign);
}

BOOST_AUTO_TEST_CASE(key_serialization)
{
{
DataStream s{};
CKey key;
BOOST_CHECK_EXCEPTION(s << key, std::ios_base::failure,
HasReason{"invalid key"});

s << MakeByteSpan(std::vector<std::byte>(33, std::byte(0)));
BOOST_CHECK_EXCEPTION(s >> key, std::ios_base::failure,
HasReason{"invalid key"});
}

for (bool compressed : {true, false}) {
CKey key{GenerateRandomKey(/*compressed=*/compressed)};
DataStream s{};
s << key;
CKey key_copy;
s >> key_copy;
BOOST_CHECK(key == key_copy);
}
}

BOOST_AUTO_TEST_SUITE_END()

0 comments on commit ef523cd

Please sign in to comment.