+ /// Encrypts the given message, returning the encrypted version.
+ /// panics if the length of `message`, once encoded, is greater than 65535 or if the Noise
+ /// handshake has not finished.
+ pub fn encrypt_message<M: wire::Type>(&mut self, message: &M) -> Vec<u8> {
+ // Allocate a buffer with 2KB, fitting most common messages. Reserve the first 16+2 bytes
+ // for the 2-byte message type prefix and its MAC.
+ let mut res = VecWriter(Vec::with_capacity(2048));
+ res.0.resize(16 + 2, 0);
+ wire::write(message, &mut res).expect("In-memory messages must never fail to serialize");
+
+ let msg_len = res.0.len() - 16 - 2;
+ if msg_len > LN_MAX_MSG_LEN {
+ panic!("Attempted to encrypt message longer than 65535 bytes!");
+ }
+
+ match self.noise_state {
+ NoiseState::Finished { ref mut sk, ref mut sn, ref mut sck, rk: _, rn: _, rck: _ } => {
+ if *sn >= 1000 {
+ let (new_sck, new_sk) = hkdf_extract_expand_twice(sck, sk);
+ *sck = new_sck;
+ *sk = new_sk;
+ *sn = 0;
+ }
+
+ Self::encrypt_with_ad(&mut res.0[0..16+2], *sn, sk, &[0; 0], &(msg_len as u16).to_be_bytes());
+ *sn += 1;
+
+ Self::encrypt_in_place_with_ad(&mut res.0, 16+2, *sn, sk, &[0; 0]);
+ *sn += 1;
+ },
+ _ => panic!("Tried to encrypt a message prior to noise handshake completion"),
+ }
+
+ res.0
+ }
+