1818#include <secp256k1_schnorrsig.h>
1919#include <secp256k1_musig.h>
2020
21+ #include "random.h"
22+
2123struct signer_secrets {
2224 secp256k1_keypair keypair ;
2325 secp256k1_musig_secnonce secnonce ;
@@ -34,20 +36,14 @@ struct signer {
3436/* Create a key pair, store it in signer_secrets->keypair and signer->pubkey */
3537int create_keypair (const secp256k1_context * ctx , struct signer_secrets * signer_secrets , struct signer * signer ) {
3638 unsigned char seckey [32 ];
37- FILE * frand = fopen ("/dev/urandom" , "r" );
38- if (frand == NULL ) {
39- return 0 ;
40- }
41- do {
42- if (!fread (seckey , sizeof (seckey ), 1 , frand )) {
43- fclose (frand );
44- return 0 ;
45- }
46- /* The probability that this not a valid secret key is approximately 2^-128 */
47- } while (!secp256k1_ec_seckey_verify (ctx , seckey ));
48- fclose (frand );
49- if (!secp256k1_keypair_create (ctx , & signer_secrets -> keypair , seckey )) {
50- return 0 ;
39+ while (1 ) {
40+ if (!fill_random (seckey , sizeof (seckey ))) {
41+ printf ("Failed to generate randomness\n" );
42+ return 1 ;
43+ }
44+ if (secp256k1_keypair_create (ctx , & signer_secrets -> keypair , seckey )) {
45+ break ;
46+ }
5147 }
5248 if (!secp256k1_keypair_xonly_pub (ctx , & signer -> pubkey , NULL , & signer_secrets -> keypair )) {
5349 return 0 ;
@@ -103,21 +99,14 @@ int sign(const secp256k1_context* ctx, struct signer_secrets *signer_secrets, st
10399 secp256k1_musig_session session ;
104100
105101 for (i = 0 ; i < N_SIGNERS ; i ++ ) {
106- FILE * frand ;
107102 unsigned char seckey [32 ];
108103 unsigned char session_id [32 ];
109104 /* Create random session ID. It is absolutely necessary that the session ID
110105 * is unique for every call of secp256k1_musig_nonce_gen. Otherwise
111106 * it's trivial for an attacker to extract the secret key! */
112- frand = fopen ("/dev/urandom" , "r" );
113- if (frand == NULL ) {
114- return 0 ;
115- }
116- if (!fread (session_id , 32 , 1 , frand )) {
117- fclose (frand );
107+ if (!fill_random (session_id , sizeof (session_id ))) {
118108 return 0 ;
119109 }
120- fclose (frand );
121110 if (!secp256k1_keypair_sec (ctx , seckey , & signer_secrets [i ].keypair )) {
122111 return 0 ;
123112 }
0 commit comments