File tree Expand file tree Collapse file tree 2 files changed +49
-0
lines changed Expand file tree Collapse file tree 2 files changed +49
-0
lines changed Original file line number Diff line number Diff line change @@ -204,6 +204,7 @@ class CKey
204
204
ECDHSecret ComputeBIP324ECDHSecret (const EllSwiftPubKey& their_ellswift,
205
205
const EllSwiftPubKey& our_ellswift,
206
206
bool initiating) const ;
207
+
207
208
/* * Compute a KeyPair
208
209
*
209
210
* Wraps a `secp256k1_keypair` type.
@@ -220,6 +221,31 @@ class CKey
220
221
* Merkle root of the script tree).
221
222
*/
222
223
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
+ }
223
249
};
224
250
225
251
CKey GenerateRandomKey (bool compressed = true ) noexcept ;
Original file line number Diff line number Diff line change @@ -386,4 +386,27 @@ BOOST_AUTO_TEST_CASE(key_schnorr_tweak_smoke_test)
386
386
secp256k1_context_destroy (secp256k1_context_sign);
387
387
}
388
388
389
+ BOOST_AUTO_TEST_CASE (key_serialization)
390
+ {
391
+ {
392
+ DataStream s{};
393
+ CKey key;
394
+ BOOST_CHECK_EXCEPTION (s << key, std::ios_base::failure,
395
+ HasReason{" invalid key" });
396
+
397
+ s << MakeByteSpan (std::vector<std::byte>(33 , std::byte (0 )));
398
+ BOOST_CHECK_EXCEPTION (s >> key, std::ios_base::failure,
399
+ HasReason{" invalid key" });
400
+ }
401
+
402
+ for (bool compressed : {true , false }) {
403
+ CKey key{GenerateRandomKey (/* compressed=*/ compressed)};
404
+ DataStream s{};
405
+ s << key;
406
+ CKey key_copy;
407
+ s >> key_copy;
408
+ BOOST_CHECK (key == key_copy);
409
+ }
410
+ }
411
+
389
412
BOOST_AUTO_TEST_SUITE_END ()
You can’t perform that action at this time.
0 commit comments