Skip to content

Commit

Permalink
Use chacha20 - Iterating nonce approach
Browse files Browse the repository at this point in the history
  • Loading branch information
danielgranhao committed Jan 26, 2023
1 parent a918567 commit 6472af6
Showing 1 changed file with 14 additions and 12 deletions.
26 changes: 14 additions & 12 deletions lightning/src/chain/keysinterface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,9 @@ use crate::ln::script::ShutdownScript;
use crate::prelude::*;
use core::convert::TryInto;
use core::sync::atomic::{AtomicUsize, Ordering};
use crate::sync::Mutex;
use crate::io::{self, Error};
use crate::ln::msgs::{DecodeError, MAX_VALUE_MSAT};
use crate::util::atomic_counter::AtomicCounter;
use crate::util::chacha20::ChaCha20;
use crate::util::invoice::construct_invoice_preimage;

Expand Down Expand Up @@ -980,7 +980,8 @@ pub struct KeysManager {
channel_master_key: ExtendedPrivKey,
channel_child_index: AtomicUsize,

chacha: Mutex<ChaCha20>,
rand_bytes_unique_start: [u8; 32],
rand_bytes_index: AtomicCounter,

seed: [u8; 32],
starting_time_secs: u64,
Expand Down Expand Up @@ -1030,10 +1031,11 @@ impl KeysManager {
let mut inbound_pmt_key_bytes = [0; 32];
inbound_pmt_key_bytes.copy_from_slice(&inbound_payment_key[..]);

let mut nonce = [0u8; 12];
nonce[..8].copy_from_slice(&starting_time_secs.to_be_bytes());
nonce[8..12].copy_from_slice(&starting_time_nanos.to_be_bytes());
let chacha = Mutex::new(ChaCha20::new(seed, &nonce));
let mut rand_bytes_unique_start = Sha256::engine();
rand_bytes_unique_start.input(&starting_time_secs.to_be_bytes());
rand_bytes_unique_start.input(&starting_time_nanos.to_be_bytes());
rand_bytes_unique_start.input(seed);
let rand_bytes_unique_start = Sha256::from_engine(rand_bytes_unique_start).into_inner();

let mut res = KeysManager {
secp_ctx,
Expand All @@ -1047,7 +1049,8 @@ impl KeysManager {
channel_master_key,
channel_child_index: AtomicUsize::new(0),

chacha,
rand_bytes_unique_start,
rand_bytes_index: AtomicCounter::new(),

seed: *seed,
starting_time_secs,
Expand Down Expand Up @@ -1244,11 +1247,10 @@ impl KeysManager {

impl EntropySource for KeysManager {
fn get_secure_random_bytes(&self) -> [u8; 32] {
let mut chacha = self.chacha.lock().unwrap();

let mut random_bytes = [0u8; 32];
chacha.process_in_place(&mut random_bytes);
random_bytes
let index = self.rand_bytes_index.get_increment();
let mut nonce = [0u8; 16];
nonce[..8].copy_from_slice(&index.to_be_bytes());
ChaCha20::get_single_block(&self.rand_bytes_unique_start, &nonce)
}
}

Expand Down

0 comments on commit 6472af6

Please sign in to comment.