Skip to content

Commit f39c5fd

Browse files
Sjorsvasild
andcommitted
CKey: add Serialize and Unserialize
Co-authored-by: Vasil Dimov <[email protected]>
1 parent 30f276a commit f39c5fd

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

src/key.h

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,7 @@ class CKey
204204
ECDHSecret ComputeBIP324ECDHSecret(const EllSwiftPubKey& their_ellswift,
205205
const EllSwiftPubKey& our_ellswift,
206206
bool initiating) const;
207+
207208
/** Compute a KeyPair
208209
*
209210
* Wraps a `secp256k1_keypair` type.
@@ -220,6 +221,31 @@ class CKey
220221
* Merkle root of the script tree).
221222
*/
222223
KeyPair ComputeKeyPair(const uint256* merkle_root) const;
224+
225+
/** Straight-forward serialization of key bytes (and compressed flag).
226+
* Use GetPrivKey() for OpenSSL compatible DER encoding.
227+
*/
228+
template <typename Stream>
229+
void Serialize(Stream& s) const
230+
{
231+
if (!IsValid()) {
232+
throw std::ios_base::failure("invalid key");
233+
}
234+
s << fCompressed;
235+
::Serialize(s, Span{*this});
236+
}
237+
238+
template <typename Stream>
239+
void Unserialize(Stream& s)
240+
{
241+
s >> fCompressed;
242+
MakeKeyData();
243+
s >> Span{*keydata};
244+
if (!Check(keydata->data())) {
245+
ClearKeyData();
246+
throw std::ios_base::failure("invalid key");
247+
}
248+
}
223249
};
224250

225251
CKey GenerateRandomKey(bool compressed = true) noexcept;

src/test/key_tests.cpp

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -390,4 +390,27 @@ BOOST_AUTO_TEST_CASE(key_schnorr_tweak_smoke_test)
390390
secp256k1_context_destroy(secp256k1_context_sign);
391391
}
392392

393+
BOOST_AUTO_TEST_CASE(key_serialization)
394+
{
395+
{
396+
DataStream s{};
397+
CKey key;
398+
BOOST_CHECK_EXCEPTION(s << key, std::ios_base::failure,
399+
HasReason{"invalid key"});
400+
401+
s << MakeByteSpan(std::vector<std::byte>(33, std::byte(0)));
402+
BOOST_CHECK_EXCEPTION(s >> key, std::ios_base::failure,
403+
HasReason{"invalid key"});
404+
}
405+
406+
for (bool compressed : {true, false}) {
407+
CKey key{GenerateRandomKey(/*compressed=*/compressed)};
408+
DataStream s{};
409+
s << key;
410+
CKey key_copy;
411+
s >> key_copy;
412+
BOOST_CHECK(key == key_copy);
413+
}
414+
}
415+
393416
BOOST_AUTO_TEST_SUITE_END()

0 commit comments

Comments
 (0)