Skip to content

Commit 6472af6

Browse files
committed
Use chacha20 - Iterating nonce approach
1 parent a918567 commit 6472af6

File tree

1 file changed

+14
-12
lines changed

1 file changed

+14
-12
lines changed

lightning/src/chain/keysinterface.rs

+14-12
Original file line numberDiff line numberDiff line change
@@ -46,9 +46,9 @@ use crate::ln::script::ShutdownScript;
4646
use crate::prelude::*;
4747
use core::convert::TryInto;
4848
use core::sync::atomic::{AtomicUsize, Ordering};
49-
use crate::sync::Mutex;
5049
use crate::io::{self, Error};
5150
use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
51+
use crate::util::atomic_counter::AtomicCounter;
5252
use crate::util::chacha20::ChaCha20;
5353
use 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

12451248
impl 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

Comments
 (0)