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 Jul 19, 2024
1 parent d47fe93 commit 3fbce5f
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/key.h
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,31 @@ class CKey
ECDHSecret ComputeBIP324ECDHSecret(const EllSwiftPubKey& their_ellswift,
const EllSwiftPubKey& our_ellswift,
bool initiating) 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 @@ -345,4 +345,27 @@ BOOST_AUTO_TEST_CASE(bip341_test_h)
BOOST_CHECK(XOnlyPubKey::NUMS_H == H);
}

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 3fbce5f

Please sign in to comment.