]> git.bitcoin.ninja Git - rust-lightning/commitdiff
Make `ChaCha20::get_single_block` return a full, single block
authorMatt Corallo <git@bluematt.me>
Tue, 16 Jan 2024 19:53:39 +0000 (19:53 +0000)
committerMatt Corallo <git@bluematt.me>
Wed, 2 Oct 2024 19:07:25 +0000 (19:07 +0000)
While the current uses for `ChaCha20::get_single_block` only
actually want 32 bytes, a ChaCha20 block is 64 bytes, and future
uses may want another 32 bytes, so we can go ahead and return the
whole block when asked for one.

lightning/src/crypto/chacha20.rs
lightning/src/sign/mod.rs

index a4df620df242d4b0e998e728f038c2b4af83c173..81e4761c0a15dd22c236994a51b0facf74607cbc 100644 (file)
@@ -152,15 +152,14 @@ mod real_chacha {
                }
 
                /// Get one block from a ChaCha stream.
-               pub fn get_single_block(key: &[u8; 32], nonce: &[u8; 16]) -> [u8; 32] {
+               pub fn get_single_block(key: &[u8; 32], nonce: &[u8; 16]) -> [u8; 64] {
                        let mut chacha = ChaCha20 {
                                state: ChaCha20::expand(key, nonce),
                                output: [0u8; BLOCK_SIZE],
                                offset: 64,
                        };
-                       let mut chacha_bytes = [0; 32];
-                       chacha.process_in_place(&mut chacha_bytes);
-                       chacha_bytes
+                       chacha.update();
+                       chacha.output
                }
 
                /// Encrypts `src` into `dest` using a single block from a ChaCha stream. Passing `dest` as
@@ -585,7 +584,7 @@ mod test {
                let mut chacha20 = ChaCha20::new(&key, nonce_12bytes);
                // Seek its counter to the block at counter_pos.
                chacha20.seek_to_block(u32::from_le_bytes(counter_pos.try_into().unwrap()));
-               let mut block_bytes = [0; 32];
+               let mut block_bytes = [0; 64];
                chacha20.process_in_place(&mut block_bytes);
 
                assert_eq!(ChaCha20::get_single_block(&key, &nonce_16bytes), block_bytes);
index 8ad34f2d653de9481c170ec3e709dd121a61315b..ea418edb60109c4fe0e81f756acc5005dcad15a1 100644 (file)
@@ -2507,7 +2507,10 @@ impl EntropySource for RandomBytes {
                let index = self.index.next();
                let mut nonce = [0u8; 16];
                nonce[..8].copy_from_slice(&index.to_be_bytes());
-               ChaCha20::get_single_block(&self.seed, &nonce)
+               let block = ChaCha20::get_single_block(&self.seed, &nonce);
+               let mut half_block = [0; 32];
+               half_block.copy_from_slice(&block[..32]);
+               half_block
        }
 }