Skip to content

Commit de8fd45

Browse files
committed
Add an option to in-place decrypt with ChaCha20Poly1305
In the next commit we'll use this to avoid an allocation when deserializing messages from the wire.
1 parent 2525faa commit de8fd45

File tree

1 file changed

+14
-9
lines changed

1 file changed

+14
-9
lines changed

lightning/src/util/chacha20poly1305rfc.rs

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -122,19 +122,24 @@ mod real_chachapoly {
122122
}
123123
}
124124

125-
// Decrypt in place, without checking the tag. Use `finish_and_check_tag` to check it
126-
// later when decryption finishes.
127-
//
128-
// Should never be `pub` because the public API should always enforce tag checking.
129-
pub(super) fn decrypt_in_place(&mut self, input_output: &mut [u8]) {
125+
pub fn decrypt_in_place(&mut self, input_output: &mut [u8], tag: &[u8]) -> Result<(), ()> {
126+
self.just_decrypt_in_place(input_output);
127+
if self.finish_and_check_tag(tag) { Ok(()) } else { Err(()) }
128+
}
129+
130+
/// Decrypt in place, without checking the tag. Use `finish_and_check_tag` to check it
131+
/// later when decryption finishes.
132+
///
133+
/// Should never be `pub` because the public API should always enforce tag checking.
134+
pub(super) fn just_decrypt_in_place(&mut self, input_output: &mut [u8]) {
130135
debug_assert!(self.finished == false);
131136
self.mac.input(input_output);
132137
self.data_len += input_output.len();
133138
self.cipher.process_in_place(input_output);
134139
}
135140

136-
// If we were previously decrypting with `decrypt_in_place`, this method must be used to finish
137-
// decrypting and check the tag. Returns whether or not the tag is valid.
141+
/// If we were previously decrypting with `just_decrypt_in_place`, this method must be used
142+
/// to check the tag. Returns whether or not the tag is valid.
138143
pub(super) fn finish_and_check_tag(&mut self, tag: &[u8]) -> bool {
139144
debug_assert!(self.finished == false);
140145
self.finished = true;
@@ -168,7 +173,7 @@ impl<'a, R: Read> Read for ChaChaPolyReader<'a, R> {
168173
fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
169174
let res = self.read.read(dest)?;
170175
if res > 0 {
171-
self.chacha.decrypt_in_place(&mut dest[0..res]);
176+
self.chacha.just_decrypt_in_place(&mut dest[0..res]);
172177
}
173178
Ok(res)
174179
}
@@ -313,7 +318,7 @@ mod fuzzy_chachapoly {
313318
true
314319
}
315320

316-
pub(super) fn decrypt_in_place(&mut self, _input: &mut [u8]) {
321+
pub(super) fn just_decrypt_in_place(&mut self, _input: &mut [u8]) {
317322
assert!(self.finished == false);
318323
}
319324

0 commit comments

Comments
 (0)