@@ -46,9 +46,9 @@ use crate::ln::script::ShutdownScript;
4646use crate :: prelude:: * ;
4747use core:: convert:: TryInto ;
4848use core:: sync:: atomic:: { AtomicUsize , Ordering } ;
49- use crate :: sync:: Mutex ;
5049use crate :: io:: { self , Error } ;
5150use crate :: ln:: msgs:: { DecodeError , MAX_VALUE_MSAT } ;
51+ use crate :: util:: atomic_counter:: AtomicCounter ;
5252use crate :: util:: chacha20:: ChaCha20 ;
5353use crate :: util:: invoice:: construct_invoice_preimage;
5454
@@ -980,7 +980,8 @@ pub struct KeysManager {
980980 channel_master_key : ExtendedPrivKey ,
981981 channel_child_index : AtomicUsize ,
982982
983- chacha : Mutex < ChaCha20 > ,
983+ rand_bytes_unique_start : [ u8 ; 32 ] ,
984+ rand_bytes_index : AtomicCounter ,
984985
985986 seed : [ u8 ; 32 ] ,
986987 starting_time_secs : u64 ,
@@ -1030,10 +1031,11 @@ impl KeysManager {
10301031 let mut inbound_pmt_key_bytes = [ 0 ; 32 ] ;
10311032 inbound_pmt_key_bytes. copy_from_slice ( & inbound_payment_key[ ..] ) ;
10321033
1033- let mut nonce = [ 0u8 ; 12 ] ;
1034- nonce[ ..8 ] . copy_from_slice ( & starting_time_secs. to_be_bytes ( ) ) ;
1035- nonce[ 8 ..12 ] . copy_from_slice ( & starting_time_nanos. to_be_bytes ( ) ) ;
1036- let chacha = Mutex :: new ( ChaCha20 :: new ( seed, & nonce) ) ;
1034+ let mut rand_bytes_unique_start = Sha256 :: engine ( ) ;
1035+ rand_bytes_unique_start. input ( & starting_time_secs. to_be_bytes ( ) ) ;
1036+ rand_bytes_unique_start. input ( & starting_time_nanos. to_be_bytes ( ) ) ;
1037+ rand_bytes_unique_start. input ( seed) ;
1038+ let rand_bytes_unique_start = Sha256 :: from_engine ( rand_bytes_unique_start) . into_inner ( ) ;
10371039
10381040 let mut res = KeysManager {
10391041 secp_ctx,
@@ -1047,7 +1049,8 @@ impl KeysManager {
10471049 channel_master_key,
10481050 channel_child_index : AtomicUsize :: new ( 0 ) ,
10491051
1050- chacha,
1052+ rand_bytes_unique_start,
1053+ rand_bytes_index : AtomicCounter :: new ( ) ,
10511054
10521055 seed : * seed,
10531056 starting_time_secs,
@@ -1244,11 +1247,10 @@ impl KeysManager {
12441247
12451248impl EntropySource for KeysManager {
12461249 fn get_secure_random_bytes ( & self ) -> [ u8 ; 32 ] {
1247- let mut chacha = self . chacha . lock ( ) . unwrap ( ) ;
1248-
1249- let mut random_bytes = [ 0u8 ; 32 ] ;
1250- chacha. process_in_place ( & mut random_bytes) ;
1251- random_bytes
1250+ let index = self . rand_bytes_index . get_increment ( ) ;
1251+ let mut nonce = [ 0u8 ; 16 ] ;
1252+ nonce[ ..8 ] . copy_from_slice ( & index. to_be_bytes ( ) ) ;
1253+ ChaCha20 :: get_single_block ( & self . rand_bytes_unique_start , & nonce)
12521254 }
12531255}
12541256
0 commit comments