]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/ln/peer_channel_encryptor.rs
8b276990cb689846680fa7de24070a4a433325de
[rust-lightning] / lightning / src / ln / peer_channel_encryptor.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 use crate::prelude::*;
11
12 use crate::sign::{NodeSigner, Recipient};
13 use crate::ln::msgs::LightningError;
14 use crate::ln::msgs;
15 use crate::ln::wire;
16
17 use bitcoin::hashes::{Hash, HashEngine};
18 use bitcoin::hashes::sha256::Hash as Sha256;
19
20 use bitcoin::secp256k1::Secp256k1;
21 use bitcoin::secp256k1::{PublicKey,SecretKey};
22 use bitcoin::secp256k1::ecdh::SharedSecret;
23 use bitcoin::secp256k1;
24
25 use crate::util::chacha20poly1305rfc::ChaCha20Poly1305RFC;
26 use crate::util::crypto::hkdf_extract_expand_twice;
27 use crate::util::ser::VecWriter;
28 use bitcoin::hashes::hex::ToHex;
29
30 use core::ops::Deref;
31
32 /// Maximum Lightning message data length according to
33 /// [BOLT-8](https://github.com/lightning/bolts/blob/v1.0/08-transport.md#lightning-message-specification)
34 /// and [BOLT-1](https://github.com/lightning/bolts/blob/master/01-messaging.md#lightning-message-format):
35 pub const LN_MAX_MSG_LEN: usize = ::core::u16::MAX as usize; // Must be equal to 65535
36
37 /// The (rough) size buffer to pre-allocate when encoding a message. Messages should reliably be
38 /// smaller than this size by at least 32 bytes or so.
39 pub const MSG_BUF_ALLOC_SIZE: usize = 2048;
40
41 // Sha256("Noise_XK_secp256k1_ChaChaPoly_SHA256")
42 const NOISE_CK: [u8; 32] = [0x26, 0x40, 0xf5, 0x2e, 0xeb, 0xcd, 0x9e, 0x88, 0x29, 0x58, 0x95, 0x1c, 0x79, 0x42, 0x50, 0xee, 0xdb, 0x28, 0x00, 0x2c, 0x05, 0xd7, 0xdc, 0x2e, 0xa0, 0xf1, 0x95, 0x40, 0x60, 0x42, 0xca, 0xf1];
43 // Sha256(NOISE_CK || "lightning")
44 const NOISE_H: [u8; 32] = [0xd1, 0xfb, 0xf6, 0xde, 0xe4, 0xf6, 0x86, 0xf1, 0x32, 0xfd, 0x70, 0x2c, 0x4a, 0xbf, 0x8f, 0xba, 0x4b, 0xb4, 0x20, 0xd8, 0x9d, 0x2a, 0x04, 0x8a, 0x3c, 0x4f, 0x4c, 0x09, 0x2e, 0x37, 0xb6, 0x76];
45
46 enum NoiseSecretKey<'a, 'b, NS: Deref> where NS::Target: NodeSigner {
47         InMemory(&'a SecretKey),
48         NodeSigner(&'b NS)
49 }
50
51 pub enum NextNoiseStep {
52         ActOne,
53         ActTwo,
54         ActThree,
55         NoiseComplete,
56 }
57
58 #[derive(PartialEq)]
59 enum NoiseStep {
60         PreActOne,
61         PostActOne,
62         PostActTwo,
63         // When done swap noise_state for NoiseState::Finished
64 }
65
66 struct BidirectionalNoiseState {
67         h: [u8; 32],
68         ck: [u8; 32],
69 }
70 enum DirectionalNoiseState {
71         Outbound {
72                 ie: SecretKey,
73         },
74         Inbound {
75                 ie: Option<PublicKey>, // filled in if state >= PostActOne
76                 re: Option<SecretKey>, // filled in if state >= PostActTwo
77                 temp_k2: Option<[u8; 32]>, // filled in if state >= PostActTwo
78         }
79 }
80 enum NoiseState {
81         InProgress {
82                 state: NoiseStep,
83                 directional_state: DirectionalNoiseState,
84                 bidirectional_state: BidirectionalNoiseState,
85         },
86         Finished {
87                 sk: [u8; 32],
88                 sn: u64,
89                 sck: [u8; 32],
90                 rk: [u8; 32],
91                 rn: u64,
92                 rck: [u8; 32],
93         }
94 }
95
96 pub struct PeerChannelEncryptor {
97         their_node_id: Option<PublicKey>, // filled in for outbound, or inbound after noise_state is Finished
98
99         noise_state: NoiseState,
100 }
101
102 impl PeerChannelEncryptor {
103         pub fn new_outbound(their_node_id: PublicKey, ephemeral_key: SecretKey) -> PeerChannelEncryptor {
104                 let mut sha = Sha256::engine();
105                 sha.input(&NOISE_H);
106                 sha.input(&their_node_id.serialize()[..]);
107                 let h = Sha256::from_engine(sha).into_inner();
108
109                 PeerChannelEncryptor {
110                         their_node_id: Some(their_node_id),
111                         noise_state: NoiseState::InProgress {
112                                 state: NoiseStep::PreActOne,
113                                 directional_state: DirectionalNoiseState::Outbound {
114                                         ie: ephemeral_key,
115                                 },
116                                 bidirectional_state: BidirectionalNoiseState {
117                                         h,
118                                         ck: NOISE_CK,
119                                 },
120                         }
121                 }
122         }
123
124         pub fn new_inbound<NS: Deref>(node_signer: &NS) -> PeerChannelEncryptor where NS::Target: NodeSigner {
125                 let mut sha = Sha256::engine();
126                 sha.input(&NOISE_H);
127                 let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap();
128                 sha.input(&our_node_id.serialize()[..]);
129                 let h = Sha256::from_engine(sha).into_inner();
130
131                 PeerChannelEncryptor {
132                         their_node_id: None,
133                         noise_state: NoiseState::InProgress {
134                                 state: NoiseStep::PreActOne,
135                                 directional_state: DirectionalNoiseState::Inbound {
136                                         ie: None,
137                                         re: None,
138                                         temp_k2: None,
139                                 },
140                                 bidirectional_state: BidirectionalNoiseState {
141                                         h,
142                                         ck: NOISE_CK,
143                                 },
144                         }
145                 }
146         }
147
148         #[inline]
149         fn encrypt_with_ad(res: &mut[u8], n: u64, key: &[u8; 32], h: &[u8], plaintext: &[u8]) {
150                 let mut nonce = [0; 12];
151                 nonce[4..].copy_from_slice(&n.to_le_bytes()[..]);
152
153                 let mut chacha = ChaCha20Poly1305RFC::new(key, &nonce, h);
154                 let mut tag = [0; 16];
155                 chacha.encrypt(plaintext, &mut res[0..plaintext.len()], &mut tag);
156                 res[plaintext.len()..].copy_from_slice(&tag);
157         }
158
159         #[inline]
160         /// Encrypts the message in res[offset..] in-place and pushes a 16-byte tag onto the end of
161         /// res.
162         fn encrypt_in_place_with_ad(res: &mut Vec<u8>, offset: usize, n: u64, key: &[u8; 32], h: &[u8]) {
163                 let mut nonce = [0; 12];
164                 nonce[4..].copy_from_slice(&n.to_le_bytes()[..]);
165
166                 let mut chacha = ChaCha20Poly1305RFC::new(key, &nonce, h);
167                 let mut tag = [0; 16];
168                 chacha.encrypt_full_message_in_place(&mut res[offset..], &mut tag);
169                 res.extend_from_slice(&tag);
170         }
171
172         fn decrypt_in_place_with_ad(inout: &mut [u8], n: u64, key: &[u8; 32], h: &[u8]) -> Result<(), LightningError> {
173                 let mut nonce = [0; 12];
174                 nonce[4..].copy_from_slice(&n.to_le_bytes()[..]);
175
176                 let mut chacha = ChaCha20Poly1305RFC::new(key, &nonce, h);
177                 let (inout, tag) = inout.split_at_mut(inout.len() - 16);
178                 if chacha.check_decrypt_in_place(inout, tag).is_err() {
179                         return Err(LightningError{err: "Bad MAC".to_owned(), action: msgs::ErrorAction::DisconnectPeer{ msg: None }});
180                 }
181                 Ok(())
182         }
183
184         #[inline]
185         fn decrypt_with_ad(res: &mut[u8], n: u64, key: &[u8; 32], h: &[u8], cyphertext: &[u8]) -> Result<(), LightningError> {
186                 let mut nonce = [0; 12];
187                 nonce[4..].copy_from_slice(&n.to_le_bytes()[..]);
188
189                 let mut chacha = ChaCha20Poly1305RFC::new(key, &nonce, h);
190                 if !chacha.decrypt(&cyphertext[0..cyphertext.len() - 16], res, &cyphertext[cyphertext.len() - 16..]) {
191                         return Err(LightningError{err: "Bad MAC".to_owned(), action: msgs::ErrorAction::DisconnectPeer{ msg: None }});
192                 }
193                 Ok(())
194         }
195
196         #[inline]
197         fn hkdf(state: &mut BidirectionalNoiseState, ss: SharedSecret) -> [u8; 32] {
198                 let (t1, t2) = hkdf_extract_expand_twice(&state.ck, ss.as_ref());
199                 state.ck = t1;
200                 t2
201         }
202
203         #[inline]
204         fn outbound_noise_act<T: secp256k1::Signing>(secp_ctx: &Secp256k1<T>, state: &mut BidirectionalNoiseState, our_key: &SecretKey, their_key: &PublicKey) -> ([u8; 50], [u8; 32]) {
205                 let our_pub = PublicKey::from_secret_key(secp_ctx, &our_key);
206
207                 let mut sha = Sha256::engine();
208                 sha.input(&state.h);
209                 sha.input(&our_pub.serialize()[..]);
210                 state.h = Sha256::from_engine(sha).into_inner();
211
212                 let ss = SharedSecret::new(&their_key, &our_key);
213                 let temp_k = PeerChannelEncryptor::hkdf(state, ss);
214
215                 let mut res = [0; 50];
216                 res[1..34].copy_from_slice(&our_pub.serialize()[..]);
217                 PeerChannelEncryptor::encrypt_with_ad(&mut res[34..], 0, &temp_k, &state.h, &[0; 0]);
218
219                 let mut sha = Sha256::engine();
220                 sha.input(&state.h);
221                 sha.input(&res[34..]);
222                 state.h = Sha256::from_engine(sha).into_inner();
223
224                 (res, temp_k)
225         }
226
227         #[inline]
228         fn inbound_noise_act<'a, 'b, NS: Deref>(
229                 state: &mut BidirectionalNoiseState, act: &[u8], secret_key: NoiseSecretKey<'a, 'b, NS>
230         ) -> Result<(PublicKey, [u8; 32]), LightningError> where NS::Target: NodeSigner {
231                 assert_eq!(act.len(), 50);
232
233                 if act[0] != 0 {
234                         return Err(LightningError{err: format!("Unknown handshake version number {}", act[0]), action: msgs::ErrorAction::DisconnectPeer{ msg: None }});
235                 }
236
237                 let their_pub = match PublicKey::from_slice(&act[1..34]) {
238                         Err(_) => return Err(LightningError{err: format!("Invalid public key {}", &act[1..34].to_hex()), action: msgs::ErrorAction::DisconnectPeer{ msg: None }}),
239                         Ok(key) => key,
240                 };
241
242                 let mut sha = Sha256::engine();
243                 sha.input(&state.h);
244                 sha.input(&their_pub.serialize()[..]);
245                 state.h = Sha256::from_engine(sha).into_inner();
246
247                 let ss = match secret_key {
248                         NoiseSecretKey::InMemory(secret_key) => SharedSecret::new(&their_pub, secret_key),
249                         NoiseSecretKey::NodeSigner(node_signer) => node_signer
250                                 .ecdh(Recipient::Node, &their_pub, None)
251                                 .map_err(|_| LightningError {
252                                         err: "Failed to derive shared secret".to_owned(),
253                                         action: msgs::ErrorAction::DisconnectPeer { msg: None }
254                                 })?,
255                 };
256                 let temp_k = PeerChannelEncryptor::hkdf(state, ss);
257
258                 let mut dec = [0; 0];
259                 PeerChannelEncryptor::decrypt_with_ad(&mut dec, 0, &temp_k, &state.h, &act[34..])?;
260
261                 let mut sha = Sha256::engine();
262                 sha.input(&state.h);
263                 sha.input(&act[34..]);
264                 state.h = Sha256::from_engine(sha).into_inner();
265
266                 Ok((their_pub, temp_k))
267         }
268
269         pub fn get_act_one<C: secp256k1::Signing>(&mut self, secp_ctx: &Secp256k1<C>) -> [u8; 50] {
270                 match self.noise_state {
271                         NoiseState::InProgress { ref mut state, ref directional_state, ref mut bidirectional_state } =>
272                                 match directional_state {
273                                         &DirectionalNoiseState::Outbound { ref ie } => {
274                                                 if *state != NoiseStep::PreActOne {
275                                                         panic!("Requested act at wrong step");
276                                                 }
277
278                                                 let (res, _) = PeerChannelEncryptor::outbound_noise_act(secp_ctx, bidirectional_state, &ie, &self.their_node_id.unwrap());
279                                                 *state = NoiseStep::PostActOne;
280                                                 res
281                                         },
282                                         _ => panic!("Wrong direction for act"),
283                                 },
284                         _ => panic!("Cannot get act one after noise handshake completes"),
285                 }
286         }
287
288         pub fn process_act_one_with_keys<C: secp256k1::Signing, NS: Deref>(
289                 &mut self, act_one: &[u8], node_signer: &NS, our_ephemeral: SecretKey, secp_ctx: &Secp256k1<C>)
290         -> Result<[u8; 50], LightningError> where NS::Target: NodeSigner {
291                 assert_eq!(act_one.len(), 50);
292
293                 match self.noise_state {
294                         NoiseState::InProgress { ref mut state, ref mut directional_state, ref mut bidirectional_state } =>
295                                 match directional_state {
296                                         &mut DirectionalNoiseState::Inbound { ref mut ie, ref mut re, ref mut temp_k2 } => {
297                                                 if *state != NoiseStep::PreActOne {
298                                                         panic!("Requested act at wrong step");
299                                                 }
300
301                                                 let (their_pub, _) = PeerChannelEncryptor::inbound_noise_act(bidirectional_state, act_one, NoiseSecretKey::NodeSigner(node_signer))?;
302                                                 ie.get_or_insert(their_pub);
303
304                                                 re.get_or_insert(our_ephemeral);
305
306                                                 let (res, temp_k) =
307                                                         PeerChannelEncryptor::outbound_noise_act(secp_ctx, bidirectional_state, &re.unwrap(), &ie.unwrap());
308                                                 *temp_k2 = Some(temp_k);
309                                                 *state = NoiseStep::PostActTwo;
310                                                 Ok(res)
311                                         },
312                                         _ => panic!("Wrong direction for act"),
313                                 },
314                         _ => panic!("Cannot get act one after noise handshake completes"),
315                 }
316         }
317
318         pub fn process_act_two<NS: Deref>(
319                 &mut self, act_two: &[u8], node_signer: &NS)
320         -> Result<([u8; 66], PublicKey), LightningError> where NS::Target: NodeSigner {
321                 assert_eq!(act_two.len(), 50);
322
323                 let final_hkdf;
324                 let ck;
325                 let res: [u8; 66] = match self.noise_state {
326                         NoiseState::InProgress { ref state, ref directional_state, ref mut bidirectional_state } =>
327                                 match directional_state {
328                                         &DirectionalNoiseState::Outbound { ref ie } => {
329                                                 if *state != NoiseStep::PostActOne {
330                                                         panic!("Requested act at wrong step");
331                                                 }
332
333                                                 let (re, temp_k2) = PeerChannelEncryptor::inbound_noise_act(bidirectional_state, act_two, NoiseSecretKey::<NS>::InMemory(&ie))?;
334
335                                                 let mut res = [0; 66];
336                                                 let our_node_id = node_signer.get_node_id(Recipient::Node).map_err(|_| LightningError {
337                                                         err: "Failed to encrypt message".to_owned(),
338                                                         action: msgs::ErrorAction::DisconnectPeer { msg: None }
339                                                 })?;
340
341                                                 PeerChannelEncryptor::encrypt_with_ad(&mut res[1..50], 1, &temp_k2, &bidirectional_state.h, &our_node_id.serialize()[..]);
342
343                                                 let mut sha = Sha256::engine();
344                                                 sha.input(&bidirectional_state.h);
345                                                 sha.input(&res[1..50]);
346                                                 bidirectional_state.h = Sha256::from_engine(sha).into_inner();
347
348                                                 let ss = node_signer.ecdh(Recipient::Node, &re, None).map_err(|_| LightningError {
349                                                         err: "Failed to derive shared secret".to_owned(),
350                                                         action: msgs::ErrorAction::DisconnectPeer { msg: None }
351                                                 })?;
352                                                 let temp_k = PeerChannelEncryptor::hkdf(bidirectional_state, ss);
353
354                                                 PeerChannelEncryptor::encrypt_with_ad(&mut res[50..], 0, &temp_k, &bidirectional_state.h, &[0; 0]);
355                                                 final_hkdf = hkdf_extract_expand_twice(&bidirectional_state.ck, &[0; 0]);
356                                                 ck = bidirectional_state.ck.clone();
357                                                 res
358                                         },
359                                         _ => panic!("Wrong direction for act"),
360                                 },
361                         _ => panic!("Cannot get act one after noise handshake completes"),
362                 };
363
364                 let (sk, rk) = final_hkdf;
365                 self.noise_state = NoiseState::Finished {
366                         sk,
367                         sn: 0,
368                         sck: ck.clone(),
369                         rk,
370                         rn: 0,
371                         rck: ck,
372                 };
373
374                 Ok((res, self.their_node_id.unwrap().clone()))
375         }
376
377         pub fn process_act_three(&mut self, act_three: &[u8]) -> Result<PublicKey, LightningError> {
378                 assert_eq!(act_three.len(), 66);
379
380                 let final_hkdf;
381                 let ck;
382                 match self.noise_state {
383                         NoiseState::InProgress { ref state, ref directional_state, ref mut bidirectional_state } =>
384                                 match directional_state {
385                                         &DirectionalNoiseState::Inbound { ie: _, ref re, ref temp_k2 } => {
386                                                 if *state != NoiseStep::PostActTwo {
387                                                         panic!("Requested act at wrong step");
388                                                 }
389                                                 if act_three[0] != 0 {
390                                                         return Err(LightningError{err: format!("Unknown handshake version number {}", act_three[0]), action: msgs::ErrorAction::DisconnectPeer{ msg: None }});
391                                                 }
392
393                                                 let mut their_node_id = [0; 33];
394                                                 PeerChannelEncryptor::decrypt_with_ad(&mut their_node_id, 1, &temp_k2.unwrap(), &bidirectional_state.h, &act_three[1..50])?;
395                                                 self.their_node_id = Some(match PublicKey::from_slice(&their_node_id) {
396                                                         Ok(key) => key,
397                                                         Err(_) => return Err(LightningError{err: format!("Bad node_id from peer, {}", &their_node_id.to_hex()), action: msgs::ErrorAction::DisconnectPeer{ msg: None }}),
398                                                 });
399
400                                                 let mut sha = Sha256::engine();
401                                                 sha.input(&bidirectional_state.h);
402                                                 sha.input(&act_three[1..50]);
403                                                 bidirectional_state.h = Sha256::from_engine(sha).into_inner();
404
405                                                 let ss = SharedSecret::new(&self.their_node_id.unwrap(), &re.unwrap());
406                                                 let temp_k = PeerChannelEncryptor::hkdf(bidirectional_state, ss);
407
408                                                 PeerChannelEncryptor::decrypt_with_ad(&mut [0; 0], 0, &temp_k, &bidirectional_state.h, &act_three[50..])?;
409                                                 final_hkdf = hkdf_extract_expand_twice(&bidirectional_state.ck, &[0; 0]);
410                                                 ck = bidirectional_state.ck.clone();
411                                         },
412                                         _ => panic!("Wrong direction for act"),
413                                 },
414                         _ => panic!("Cannot get act one after noise handshake completes"),
415                 }
416
417                 let (rk, sk) = final_hkdf;
418                 self.noise_state = NoiseState::Finished {
419                         sk,
420                         sn: 0,
421                         sck: ck.clone(),
422                         rk,
423                         rn: 0,
424                         rck: ck,
425                 };
426
427                 Ok(self.their_node_id.unwrap().clone())
428         }
429
430         /// Encrypts the given pre-serialized message, returning the encrypted version.
431         /// panics if msg.len() > 65535 or Noise handshake has not finished.
432         pub fn encrypt_buffer(&mut self, msg: &[u8]) -> Vec<u8> {
433                 if msg.len() > LN_MAX_MSG_LEN {
434                         panic!("Attempted to encrypt message longer than 65535 bytes!");
435                 }
436
437                 let mut res = Vec::with_capacity(msg.len() + 16*2 + 2);
438                 res.resize(msg.len() + 16*2 + 2, 0);
439
440                 match self.noise_state {
441                         NoiseState::Finished { ref mut sk, ref mut sn, ref mut sck, rk: _, rn: _, rck: _ } => {
442                                 if *sn >= 1000 {
443                                         let (new_sck, new_sk) = hkdf_extract_expand_twice(sck, sk);
444                                         *sck = new_sck;
445                                         *sk = new_sk;
446                                         *sn = 0;
447                                 }
448
449                                 Self::encrypt_with_ad(&mut res[0..16+2], *sn, sk, &[0; 0], &(msg.len() as u16).to_be_bytes());
450                                 *sn += 1;
451
452                                 Self::encrypt_with_ad(&mut res[16+2..], *sn, sk, &[0; 0], msg);
453                                 *sn += 1;
454                         },
455                         _ => panic!("Tried to encrypt a message prior to noise handshake completion"),
456                 }
457
458                 res
459         }
460
461         /// Encrypts the given message, returning the encrypted version.
462         /// panics if the length of `message`, once encoded, is greater than 65535 or if the Noise
463         /// handshake has not finished.
464         pub fn encrypt_message<M: wire::Type>(&mut self, message: &M) -> Vec<u8> {
465                 // Allocate a buffer with 2KB, fitting most common messages. Reserve the first 16+2 bytes
466                 // for the 2-byte message type prefix and its MAC.
467                 let mut res = VecWriter(Vec::with_capacity(MSG_BUF_ALLOC_SIZE));
468                 res.0.resize(16 + 2, 0);
469                 wire::write(message, &mut res).expect("In-memory messages must never fail to serialize");
470
471                 let msg_len = res.0.len() - 16 - 2;
472                 if msg_len > LN_MAX_MSG_LEN {
473                         panic!("Attempted to encrypt message longer than 65535 bytes!");
474                 }
475
476                 match self.noise_state {
477                         NoiseState::Finished { ref mut sk, ref mut sn, ref mut sck, rk: _, rn: _, rck: _ } => {
478                                 if *sn >= 1000 {
479                                         let (new_sck, new_sk) = hkdf_extract_expand_twice(sck, sk);
480                                         *sck = new_sck;
481                                         *sk = new_sk;
482                                         *sn = 0;
483                                 }
484
485                                 Self::encrypt_with_ad(&mut res.0[0..16+2], *sn, sk, &[0; 0], &(msg_len as u16).to_be_bytes());
486                                 *sn += 1;
487
488                                 Self::encrypt_in_place_with_ad(&mut res.0, 16+2, *sn, sk, &[0; 0]);
489                                 *sn += 1;
490                         },
491                         _ => panic!("Tried to encrypt a message prior to noise handshake completion"),
492                 }
493
494                 res.0
495         }
496
497         /// Decrypts a message length header from the remote peer.
498         /// panics if noise handshake has not yet finished or msg.len() != 18
499         pub fn decrypt_length_header(&mut self, msg: &[u8]) -> Result<u16, LightningError> {
500                 assert_eq!(msg.len(), 16+2);
501
502                 match self.noise_state {
503                         NoiseState::Finished { sk: _, sn: _, sck: _, ref mut rk, ref mut rn, ref mut rck } => {
504                                 if *rn >= 1000 {
505                                         let (new_rck, new_rk) = hkdf_extract_expand_twice(rck, rk);
506                                         *rck = new_rck;
507                                         *rk = new_rk;
508                                         *rn = 0;
509                                 }
510
511                                 let mut res = [0; 2];
512                                 Self::decrypt_with_ad(&mut res, *rn, rk, &[0; 0], msg)?;
513                                 *rn += 1;
514                                 Ok(u16::from_be_bytes(res))
515                         },
516                         _ => panic!("Tried to decrypt a message prior to noise handshake completion"),
517                 }
518         }
519
520         /// Decrypts the given message up to msg.len() - 16. Bytes after msg.len() - 16 will be left
521         /// undefined (as they contain the Poly1305 tag bytes).
522         ///
523         /// panics if msg.len() > 65535 + 16
524         pub fn decrypt_message(&mut self, msg: &mut [u8]) -> Result<(), LightningError> {
525                 if msg.len() > LN_MAX_MSG_LEN + 16 {
526                         panic!("Attempted to decrypt message longer than 65535 + 16 bytes!");
527                 }
528
529                 match self.noise_state {
530                         NoiseState::Finished { sk: _, sn: _, sck: _, ref rk, ref mut rn, rck: _ } => {
531                                 Self::decrypt_in_place_with_ad(&mut msg[..], *rn, rk, &[0; 0])?;
532                                 *rn += 1;
533                                 Ok(())
534                         },
535                         _ => panic!("Tried to decrypt a message prior to noise handshake completion"),
536                 }
537         }
538
539         pub fn get_noise_step(&self) -> NextNoiseStep {
540                 match self.noise_state {
541                         NoiseState::InProgress {ref state, ..} => {
542                                 match state {
543                                         &NoiseStep::PreActOne => NextNoiseStep::ActOne,
544                                         &NoiseStep::PostActOne => NextNoiseStep::ActTwo,
545                                         &NoiseStep::PostActTwo => NextNoiseStep::ActThree,
546                                 }
547                         },
548                         NoiseState::Finished {..} => NextNoiseStep::NoiseComplete,
549                 }
550         }
551
552         pub fn is_ready_for_encryption(&self) -> bool {
553                 match self.noise_state {
554                         NoiseState::InProgress {..} => { false },
555                         NoiseState::Finished {..} => { true }
556                 }
557         }
558 }
559
560 #[cfg(test)]
561 mod tests {
562         use super::LN_MAX_MSG_LEN;
563
564         use bitcoin::secp256k1::{PublicKey, SecretKey};
565         use bitcoin::secp256k1::Secp256k1;
566
567         use hex;
568
569         use crate::ln::peer_channel_encryptor::{PeerChannelEncryptor,NoiseState};
570         use crate::util::test_utils::TestNodeSigner;
571
572         fn get_outbound_peer_for_initiator_test_vectors() -> PeerChannelEncryptor {
573                 let their_node_id = PublicKey::from_slice(&hex::decode("028d7500dd4c12685d1f568b4c2b5048e8534b873319f3a8daa612b469132ec7f7").unwrap()[..]).unwrap();
574                 let secp_ctx = Secp256k1::signing_only();
575
576                 let mut outbound_peer = PeerChannelEncryptor::new_outbound(their_node_id, SecretKey::from_slice(&hex::decode("1212121212121212121212121212121212121212121212121212121212121212").unwrap()[..]).unwrap());
577                 assert_eq!(outbound_peer.get_act_one(&secp_ctx)[..], hex::decode("00036360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6a").unwrap()[..]);
578                 outbound_peer
579         }
580
581         fn get_inbound_peer_for_test_vectors() -> PeerChannelEncryptor {
582                 // transport-responder successful handshake
583                 let our_node_id = SecretKey::from_slice(&hex::decode("2121212121212121212121212121212121212121212121212121212121212121").unwrap()[..]).unwrap();
584                 let our_ephemeral = SecretKey::from_slice(&hex::decode("2222222222222222222222222222222222222222222222222222222222222222").unwrap()[..]).unwrap();
585                 let secp_ctx = Secp256k1::new();
586                 let node_signer = TestNodeSigner::new(our_node_id);
587
588                 let mut inbound_peer = PeerChannelEncryptor::new_inbound(&&node_signer);
589
590                 let act_one = hex::decode("00036360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6a").unwrap().to_vec();
591                 assert_eq!(inbound_peer.process_act_one_with_keys(&act_one[..], &&node_signer, our_ephemeral.clone(), &secp_ctx).unwrap()[..], hex::decode("0002466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae").unwrap()[..]);
592
593                 let act_three = hex::decode("00b9e3a702e93e3a9948c2ed6e5fd7590a6e1c3a0344cfc9d5b57357049aa22355361aa02e55a8fc28fef5bd6d71ad0c38228dc68b1c466263b47fdf31e560e139ba").unwrap().to_vec();
594                 // test vector doesn't specify the initiator static key, but it's the same as the one
595                 // from transport-initiator successful handshake
596                 assert_eq!(inbound_peer.process_act_three(&act_three[..]).unwrap().serialize()[..], hex::decode("034f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa").unwrap()[..]);
597
598                 match inbound_peer.noise_state {
599                         NoiseState::Finished { sk, sn, sck, rk, rn, rck } => {
600                                 assert_eq!(sk, hex::decode("bb9020b8965f4df047e07f955f3c4b88418984aadc5cdb35096b9ea8fa5c3442").unwrap()[..]);
601                                 assert_eq!(sn, 0);
602                                 assert_eq!(sck, hex::decode("919219dbb2920afa8db80f9a51787a840bcf111ed8d588caf9ab4be716e42b01").unwrap()[..]);
603                                 assert_eq!(rk, hex::decode("969ab31b4d288cedf6218839b27a3e2140827047f2c0f01bf5c04435d43511a9").unwrap()[..]);
604                                 assert_eq!(rn, 0);
605                                 assert_eq!(rck, hex::decode("919219dbb2920afa8db80f9a51787a840bcf111ed8d588caf9ab4be716e42b01").unwrap()[..]);
606                         },
607                         _ => panic!()
608                 }
609
610                 inbound_peer
611         }
612
613         #[test]
614         fn noise_initiator_test_vectors() {
615                 let our_node_id = SecretKey::from_slice(&hex::decode("1111111111111111111111111111111111111111111111111111111111111111").unwrap()[..]).unwrap();
616                 let node_signer = TestNodeSigner::new(our_node_id);
617
618                 {
619                         // transport-initiator successful handshake
620                         let mut outbound_peer = get_outbound_peer_for_initiator_test_vectors();
621
622                         let act_two = hex::decode("0002466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae").unwrap().to_vec();
623                         assert_eq!(outbound_peer.process_act_two(&act_two[..], &&node_signer).unwrap().0[..], hex::decode("00b9e3a702e93e3a9948c2ed6e5fd7590a6e1c3a0344cfc9d5b57357049aa22355361aa02e55a8fc28fef5bd6d71ad0c38228dc68b1c466263b47fdf31e560e139ba").unwrap()[..]);
624
625                         match outbound_peer.noise_state {
626                                 NoiseState::Finished { sk, sn, sck, rk, rn, rck } => {
627                                         assert_eq!(sk, hex::decode("969ab31b4d288cedf6218839b27a3e2140827047f2c0f01bf5c04435d43511a9").unwrap()[..]);
628                                         assert_eq!(sn, 0);
629                                         assert_eq!(sck, hex::decode("919219dbb2920afa8db80f9a51787a840bcf111ed8d588caf9ab4be716e42b01").unwrap()[..]);
630                                         assert_eq!(rk, hex::decode("bb9020b8965f4df047e07f955f3c4b88418984aadc5cdb35096b9ea8fa5c3442").unwrap()[..]);
631                                         assert_eq!(rn, 0);
632                                         assert_eq!(rck, hex::decode("919219dbb2920afa8db80f9a51787a840bcf111ed8d588caf9ab4be716e42b01").unwrap()[..]);
633                                 },
634                                 _ => panic!()
635                         }
636                 }
637                 {
638                         // transport-initiator act2 short read test
639                         // Can't actually test this cause process_act_two requires you pass the right length!
640                 }
641                 {
642                         // transport-initiator act2 bad version test
643                         let mut outbound_peer = get_outbound_peer_for_initiator_test_vectors();
644
645                         let act_two = hex::decode("0102466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae").unwrap().to_vec();
646                         assert!(outbound_peer.process_act_two(&act_two[..], &&node_signer).is_err());
647                 }
648
649                 {
650                         // transport-initiator act2 bad key serialization test
651                         let mut outbound_peer = get_outbound_peer_for_initiator_test_vectors();
652
653                         let act_two = hex::decode("0004466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae").unwrap().to_vec();
654                         assert!(outbound_peer.process_act_two(&act_two[..], &&node_signer).is_err());
655                 }
656
657                 {
658                         // transport-initiator act2 bad MAC test
659                         let mut outbound_peer = get_outbound_peer_for_initiator_test_vectors();
660
661                         let act_two = hex::decode("0002466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730af").unwrap().to_vec();
662                         assert!(outbound_peer.process_act_two(&act_two[..], &&node_signer).is_err());
663                 }
664         }
665
666         #[test]
667         fn noise_responder_test_vectors() {
668                 let our_node_id = SecretKey::from_slice(&hex::decode("2121212121212121212121212121212121212121212121212121212121212121").unwrap()[..]).unwrap();
669                 let our_ephemeral = SecretKey::from_slice(&hex::decode("2222222222222222222222222222222222222222222222222222222222222222").unwrap()[..]).unwrap();
670                 let secp_ctx = Secp256k1::new();
671                 let node_signer = TestNodeSigner::new(our_node_id);
672
673                 {
674                         let _ = get_inbound_peer_for_test_vectors();
675                 }
676                 {
677                         // transport-responder act1 short read test
678                         // Can't actually test this cause process_act_one requires you pass the right length!
679                 }
680                 {
681                         // transport-responder act1 bad version test
682                         let mut inbound_peer = PeerChannelEncryptor::new_inbound(&&node_signer);
683
684                         let act_one = hex::decode("01036360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6a").unwrap().to_vec();
685                         assert!(inbound_peer.process_act_one_with_keys(&act_one[..], &&node_signer, our_ephemeral.clone(), &secp_ctx).is_err());
686                 }
687                 {
688                         // transport-responder act1 bad key serialization test
689                         let mut inbound_peer = PeerChannelEncryptor::new_inbound(&&node_signer);
690
691                         let act_one =hex::decode("00046360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6a").unwrap().to_vec();
692                         assert!(inbound_peer.process_act_one_with_keys(&act_one[..], &&node_signer, our_ephemeral.clone(), &secp_ctx).is_err());
693                 }
694                 {
695                         // transport-responder act1 bad MAC test
696                         let mut inbound_peer = PeerChannelEncryptor::new_inbound(&&node_signer);
697
698                         let act_one = hex::decode("00036360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6b").unwrap().to_vec();
699                         assert!(inbound_peer.process_act_one_with_keys(&act_one[..], &&node_signer, our_ephemeral.clone(), &secp_ctx).is_err());
700                 }
701                 {
702                         // transport-responder act3 bad version test
703                         let mut inbound_peer = PeerChannelEncryptor::new_inbound(&&node_signer);
704
705                         let act_one = hex::decode("00036360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6a").unwrap().to_vec();
706                         assert_eq!(inbound_peer.process_act_one_with_keys(&act_one[..], &&node_signer, our_ephemeral.clone(), &secp_ctx).unwrap()[..], hex::decode("0002466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae").unwrap()[..]);
707
708                         let act_three = hex::decode("01b9e3a702e93e3a9948c2ed6e5fd7590a6e1c3a0344cfc9d5b57357049aa22355361aa02e55a8fc28fef5bd6d71ad0c38228dc68b1c466263b47fdf31e560e139ba").unwrap().to_vec();
709                         assert!(inbound_peer.process_act_three(&act_three[..]).is_err());
710                 }
711                 {
712                         // transport-responder act3 short read test
713                         // Can't actually test this cause process_act_three requires you pass the right length!
714                 }
715                 {
716                         // transport-responder act3 bad MAC for ciphertext test
717                         let mut inbound_peer = PeerChannelEncryptor::new_inbound(&&node_signer);
718
719                         let act_one = hex::decode("00036360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6a").unwrap().to_vec();
720                         assert_eq!(inbound_peer.process_act_one_with_keys(&act_one[..], &&node_signer, our_ephemeral.clone(), &secp_ctx).unwrap()[..], hex::decode("0002466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae").unwrap()[..]);
721
722                         let act_three = hex::decode("00c9e3a702e93e3a9948c2ed6e5fd7590a6e1c3a0344cfc9d5b57357049aa22355361aa02e55a8fc28fef5bd6d71ad0c38228dc68b1c466263b47fdf31e560e139ba").unwrap().to_vec();
723                         assert!(inbound_peer.process_act_three(&act_three[..]).is_err());
724                 }
725                 {
726                         // transport-responder act3 bad rs test
727                         let mut inbound_peer = PeerChannelEncryptor::new_inbound(&&node_signer);
728
729                         let act_one = hex::decode("00036360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6a").unwrap().to_vec();
730                         assert_eq!(inbound_peer.process_act_one_with_keys(&act_one[..], &&node_signer, our_ephemeral.clone(), &secp_ctx).unwrap()[..], hex::decode("0002466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae").unwrap()[..]);
731
732                         let act_three = hex::decode("00bfe3a702e93e3a9948c2ed6e5fd7590a6e1c3a0344cfc9d5b57357049aa2235536ad09a8ee351870c2bb7f78b754a26c6cef79a98d25139c856d7efd252c2ae73c").unwrap().to_vec();
733                         assert!(inbound_peer.process_act_three(&act_three[..]).is_err());
734                 }
735                 {
736                         // transport-responder act3 bad MAC test
737                         let mut inbound_peer = PeerChannelEncryptor::new_inbound(&&node_signer);
738
739                         let act_one = hex::decode("00036360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6a").unwrap().to_vec();
740                         assert_eq!(inbound_peer.process_act_one_with_keys(&act_one[..], &&node_signer, our_ephemeral.clone(), &secp_ctx).unwrap()[..], hex::decode("0002466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae").unwrap()[..]);
741
742                         let act_three = hex::decode("00b9e3a702e93e3a9948c2ed6e5fd7590a6e1c3a0344cfc9d5b57357049aa22355361aa02e55a8fc28fef5bd6d71ad0c38228dc68b1c466263b47fdf31e560e139bb").unwrap().to_vec();
743                         assert!(inbound_peer.process_act_three(&act_three[..]).is_err());
744                 }
745         }
746
747
748         #[test]
749         fn message_encryption_decryption_test_vectors() {
750                 // We use the same keys as the initiator and responder test vectors, so we copy those tests
751                 // here and use them to encrypt.
752                 let mut outbound_peer = get_outbound_peer_for_initiator_test_vectors();
753
754                 {
755                         let our_node_id = SecretKey::from_slice(&hex::decode("1111111111111111111111111111111111111111111111111111111111111111").unwrap()[..]).unwrap();
756                         let node_signer = TestNodeSigner::new(our_node_id);
757
758                         let act_two = hex::decode("0002466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae").unwrap().to_vec();
759                         assert_eq!(outbound_peer.process_act_two(&act_two[..], &&node_signer).unwrap().0[..], hex::decode("00b9e3a702e93e3a9948c2ed6e5fd7590a6e1c3a0344cfc9d5b57357049aa22355361aa02e55a8fc28fef5bd6d71ad0c38228dc68b1c466263b47fdf31e560e139ba").unwrap()[..]);
760
761                         match outbound_peer.noise_state {
762                                 NoiseState::Finished { sk, sn, sck, rk, rn, rck } => {
763                                         assert_eq!(sk, hex::decode("969ab31b4d288cedf6218839b27a3e2140827047f2c0f01bf5c04435d43511a9").unwrap()[..]);
764                                         assert_eq!(sn, 0);
765                                         assert_eq!(sck, hex::decode("919219dbb2920afa8db80f9a51787a840bcf111ed8d588caf9ab4be716e42b01").unwrap()[..]);
766                                         assert_eq!(rk, hex::decode("bb9020b8965f4df047e07f955f3c4b88418984aadc5cdb35096b9ea8fa5c3442").unwrap()[..]);
767                                         assert_eq!(rn, 0);
768                                         assert_eq!(rck, hex::decode("919219dbb2920afa8db80f9a51787a840bcf111ed8d588caf9ab4be716e42b01").unwrap()[..]);
769                                 },
770                                 _ => panic!()
771                         }
772                 }
773
774                 let mut inbound_peer = get_inbound_peer_for_test_vectors();
775
776                 for i in 0..1005 {
777                         let msg = [0x68, 0x65, 0x6c, 0x6c, 0x6f];
778                         let mut res = outbound_peer.encrypt_buffer(&msg);
779                         assert_eq!(res.len(), 5 + 2*16 + 2);
780
781                         let len_header = res[0..2+16].to_vec();
782                         assert_eq!(inbound_peer.decrypt_length_header(&len_header[..]).unwrap() as usize, msg.len());
783
784                         if i == 0 {
785                                 assert_eq!(res, hex::decode("cf2b30ddf0cf3f80e7c35a6e6730b59fe802473180f396d88a8fb0db8cbcf25d2f214cf9ea1d95").unwrap());
786                         } else if i == 1 {
787                                 assert_eq!(res, hex::decode("72887022101f0b6753e0c7de21657d35a4cb2a1f5cde2650528bbc8f837d0f0d7ad833b1a256a1").unwrap());
788                         } else if i == 500 {
789                                 assert_eq!(res, hex::decode("178cb9d7387190fa34db9c2d50027d21793c9bc2d40b1e14dcf30ebeeeb220f48364f7a4c68bf8").unwrap());
790                         } else if i == 501 {
791                                 assert_eq!(res, hex::decode("1b186c57d44eb6de4c057c49940d79bb838a145cb528d6e8fd26dbe50a60ca2c104b56b60e45bd").unwrap());
792                         } else if i == 1000 {
793                                 assert_eq!(res, hex::decode("4a2f3cc3b5e78ddb83dcb426d9863d9d9a723b0337c89dd0b005d89f8d3c05c52b76b29b740f09").unwrap());
794                         } else if i == 1001 {
795                                 assert_eq!(res, hex::decode("2ecd8c8a5629d0d02ab457a0fdd0f7b90a192cd46be5ecb6ca570bfc5e268338b1a16cf4ef2d36").unwrap());
796                         }
797
798                         inbound_peer.decrypt_message(&mut res[2+16..]).unwrap();
799                         assert_eq!(res[2 + 16..res.len() - 16], msg[..]);
800                 }
801         }
802
803         #[test]
804         fn max_msg_len_limit_value() {
805                 assert_eq!(LN_MAX_MSG_LEN, 65535);
806                 assert_eq!(LN_MAX_MSG_LEN, ::core::u16::MAX as usize);
807         }
808
809         #[test]
810         #[should_panic(expected = "Attempted to encrypt message longer than 65535 bytes!")]
811         fn max_message_len_encryption() {
812                 let mut outbound_peer = get_outbound_peer_for_initiator_test_vectors();
813                 let msg = [4u8; LN_MAX_MSG_LEN + 1];
814                 outbound_peer.encrypt_buffer(&msg);
815         }
816
817         #[test]
818         #[should_panic(expected = "Attempted to decrypt message longer than 65535 + 16 bytes!")]
819         fn max_message_len_decryption() {
820                 let mut inbound_peer = get_inbound_peer_for_test_vectors();
821
822                 // MSG should not exceed LN_MAX_MSG_LEN + 16
823                 let mut msg = [4u8; LN_MAX_MSG_LEN + 17];
824                 inbound_peer.decrypt_message(&mut msg).unwrap();
825         }
826 }