@@ -52,6 +52,20 @@ secp256k1_context const* getCtx()
5252 return s_ctx.get ();
5353}
5454
55+ template <std::size_t KeySize>
56+ bool toPublicKey (Secret const & _secret, unsigned _flags, array<byte, KeySize>& o_serializedPubkey)
57+ {
58+ auto * ctx = getCtx ();
59+ secp256k1_pubkey rawPubkey;
60+ // Creation will fail if the secret key is invalid.
61+ if (!secp256k1_ec_pubkey_create (ctx, &rawPubkey, _secret.data ()))
62+ return false ;
63+ size_t serializedPubkeySize = o_serializedPubkey.size ();
64+ secp256k1_ec_pubkey_serialize (
65+ ctx, o_serializedPubkey.data (), &serializedPubkeySize, &rawPubkey, _flags);
66+ assert (serializedPubkeySize == o_serializedPubkey.size ());
67+ return true ;
68+ }
5569}
5670
5771bool dev::SignatureStruct::isValid () const noexcept
@@ -64,24 +78,29 @@ bool dev::SignatureStruct::isValid() const noexcept
6478
6579Public dev::toPublic (Secret const & _secret)
6680{
67- auto * ctx = getCtx ();
68- secp256k1_pubkey rawPubkey;
69- // Creation will fail if the secret key is invalid.
70- if (!secp256k1_ec_pubkey_create (ctx, &rawPubkey, _secret.data ()))
71- return {};
7281 std::array<byte, 65 > serializedPubkey;
73- size_t serializedPubkeySize = serializedPubkey.size ();
74- secp256k1_ec_pubkey_serialize (
75- ctx, serializedPubkey.data (), &serializedPubkeySize,
76- &rawPubkey, SECP256K1_EC_UNCOMPRESSED
77- );
78- assert (serializedPubkeySize == serializedPubkey.size ());
82+ if (!toPublicKey (_secret, SECP256K1_EC_UNCOMPRESSED, serializedPubkey))
83+ return {};
84+
7985 // Expect single byte header of value 0x04 -- uncompressed public key.
8086 assert (serializedPubkey[0 ] == 0x04 );
87+
8188 // Create the Public skipping the header.
8289 return Public{&serializedPubkey[1 ], Public::ConstructFromPointer};
8390}
8491
92+ PublicCompressed dev::toPublicCompressed (Secret const & _secret)
93+ {
94+ PublicCompressed serializedPubkey;
95+ if (!toPublicKey (_secret, SECP256K1_EC_COMPRESSED, serializedPubkey.asArray ()))
96+ return {};
97+
98+ // Expect single byte header of value 0x02 or 0x03 -- compressed public key.
99+ assert (serializedPubkey[0 ] == 0x02 || serializedPubkey[0 ] == 0x03 );
100+
101+ return serializedPubkey;
102+ }
103+
85104Address dev::toAddress (Public const & _public)
86105{
87106 return right160 (sha3 (_public.ref ()));
0 commit comments