1use crate::prelude::*;
11
12use crate::ln::msgs;
13use crate::ln::msgs::LightningError;
14use crate::ln::wire;
15use crate::sign::{NodeSigner, Recipient};
16
17use bitcoin::hashes::sha256::Hash as Sha256;
18use bitcoin::hashes::{Hash, HashEngine};
19
20use bitcoin::hex::DisplayHex;
21
22use bitcoin::secp256k1;
23use bitcoin::secp256k1::ecdh::SharedSecret;
24use bitcoin::secp256k1::Secp256k1;
25use bitcoin::secp256k1::{PublicKey, SecretKey};
26
27use crate::crypto::chacha20poly1305rfc::ChaCha20Poly1305RFC;
28use crate::crypto::utils::hkdf_extract_expand_twice;
29use crate::util::ser::VecWriter;
30
31use core::ops::Deref;
32
33pub const LN_MAX_MSG_LEN: usize = ::core::u16::MAX as usize; pub const MSG_BUF_ALLOC_SIZE: usize = 2048;
41
42const NOISE_CK: [u8; 32] = [
44 0x26, 0x40, 0xf5, 0x2e, 0xeb, 0xcd, 0x9e, 0x88, 0x29, 0x58, 0x95, 0x1c, 0x79, 0x42, 0x50, 0xee,
45 0xdb, 0x28, 0x00, 0x2c, 0x05, 0xd7, 0xdc, 0x2e, 0xa0, 0xf1, 0x95, 0x40, 0x60, 0x42, 0xca, 0xf1,
46];
47const NOISE_H: [u8; 32] = [
49 0xd1, 0xfb, 0xf6, 0xde, 0xe4, 0xf6, 0x86, 0xf1, 0x32, 0xfd, 0x70, 0x2c, 0x4a, 0xbf, 0x8f, 0xba,
50 0x4b, 0xb4, 0x20, 0xd8, 0x9d, 0x2a, 0x04, 0x8a, 0x3c, 0x4f, 0x4c, 0x09, 0x2e, 0x37, 0xb6, 0x76,
51];
52
53enum NoiseSecretKey<'a, 'b, NS: Deref>
54where
55 NS::Target: NodeSigner,
56{
57 InMemory(&'a SecretKey),
58 NodeSigner(&'b NS),
59}
60
61pub enum NextNoiseStep {
62 ActOne,
63 ActTwo,
64 ActThree,
65 NoiseComplete,
66}
67
68#[derive(PartialEq)]
69enum NoiseStep {
70 PreActOne,
71 PostActOne,
72 PostActTwo,
73 }
75
76struct BidirectionalNoiseState {
77 h: [u8; 32],
78 ck: [u8; 32],
79}
80enum DirectionalNoiseState {
81 Outbound {
82 ie: SecretKey,
83 },
84 Inbound {
85 ie: Option<PublicKey>, re: Option<SecretKey>, temp_k2: Option<[u8; 32]>, },
89}
90enum NoiseState {
91 InProgress {
92 state: NoiseStep,
93 directional_state: DirectionalNoiseState,
94 bidirectional_state: BidirectionalNoiseState,
95 },
96 Finished {
97 sk: [u8; 32],
98 sn: u64,
99 sck: [u8; 32],
100 rk: [u8; 32],
101 rn: u64,
102 rck: [u8; 32],
103 },
104}
105
106pub struct PeerChannelEncryptor {
107 their_node_id: Option<PublicKey>, noise_state: NoiseState,
110}
111
112impl PeerChannelEncryptor {
113 pub fn new_outbound(
114 their_node_id: PublicKey, ephemeral_key: SecretKey,
115 ) -> PeerChannelEncryptor {
116 let mut sha = Sha256::engine();
117 sha.input(&NOISE_H);
118 sha.input(&their_node_id.serialize()[..]);
119 let h = Sha256::from_engine(sha).to_byte_array();
120
121 PeerChannelEncryptor {
122 their_node_id: Some(their_node_id),
123 noise_state: NoiseState::InProgress {
124 state: NoiseStep::PreActOne,
125 directional_state: DirectionalNoiseState::Outbound { ie: ephemeral_key },
126 bidirectional_state: BidirectionalNoiseState { h, ck: NOISE_CK },
127 },
128 }
129 }
130
131 pub fn new_inbound<NS: Deref>(node_signer: &NS) -> PeerChannelEncryptor
132 where
133 NS::Target: NodeSigner,
134 {
135 let mut sha = Sha256::engine();
136 sha.input(&NOISE_H);
137 let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap();
138 sha.input(&our_node_id.serialize()[..]);
139 let h = Sha256::from_engine(sha).to_byte_array();
140
141 PeerChannelEncryptor {
142 their_node_id: None,
143 noise_state: NoiseState::InProgress {
144 state: NoiseStep::PreActOne,
145 directional_state: DirectionalNoiseState::Inbound {
146 ie: None,
147 re: None,
148 temp_k2: None,
149 },
150 bidirectional_state: BidirectionalNoiseState { h, ck: NOISE_CK },
151 },
152 }
153 }
154
155 #[inline]
156 fn encrypt_with_ad(res: &mut [u8], n: u64, key: &[u8; 32], h: &[u8], plaintext: &[u8]) {
157 let mut nonce = [0; 12];
158 nonce[4..].copy_from_slice(&n.to_le_bytes()[..]);
159
160 let mut chacha = ChaCha20Poly1305RFC::new(key, &nonce, h);
161 let mut tag = [0; 16];
162 chacha.encrypt(plaintext, &mut res[0..plaintext.len()], &mut tag);
163 res[plaintext.len()..].copy_from_slice(&tag);
164 }
165
166 #[inline]
167 fn encrypt_in_place_with_ad(
170 res: &mut Vec<u8>, offset: usize, n: u64, key: &[u8; 32], h: &[u8],
171 ) {
172 let mut nonce = [0; 12];
173 nonce[4..].copy_from_slice(&n.to_le_bytes()[..]);
174
175 let mut chacha = ChaCha20Poly1305RFC::new(key, &nonce, h);
176 let mut tag = [0; 16];
177 chacha.encrypt_full_message_in_place(&mut res[offset..], &mut tag);
178 res.extend_from_slice(&tag);
179 }
180
181 fn decrypt_in_place_with_ad(
182 inout: &mut [u8], n: u64, key: &[u8; 32], h: &[u8],
183 ) -> Result<(), LightningError> {
184 let mut nonce = [0; 12];
185 nonce[4..].copy_from_slice(&n.to_le_bytes()[..]);
186
187 let mut chacha = ChaCha20Poly1305RFC::new(key, &nonce, h);
188 let (inout, tag) = inout.split_at_mut(inout.len() - 16);
189 if chacha.check_decrypt_in_place(inout, tag).is_err() {
190 return Err(LightningError {
191 err: "Bad MAC".to_owned(),
192 action: msgs::ErrorAction::DisconnectPeer { msg: None },
193 });
194 }
195 Ok(())
196 }
197
198 #[inline]
199 fn decrypt_with_ad(
200 res: &mut [u8], n: u64, key: &[u8; 32], h: &[u8], cyphertext: &[u8],
201 ) -> Result<(), LightningError> {
202 let mut nonce = [0; 12];
203 nonce[4..].copy_from_slice(&n.to_le_bytes()[..]);
204
205 let (data, hmac) = cyphertext.split_at(cyphertext.len() - 16);
206 let mac_check =
207 ChaCha20Poly1305RFC::new(key, &nonce, h).variable_time_decrypt(&data, res, hmac);
208 mac_check.map_err(|()| LightningError {
209 err: "Bad MAC".to_owned(),
210 action: msgs::ErrorAction::DisconnectPeer { msg: None },
211 })
212 }
213
214 #[inline]
215 fn hkdf(state: &mut BidirectionalNoiseState, ss: SharedSecret) -> [u8; 32] {
216 let (t1, t2) = hkdf_extract_expand_twice(&state.ck, ss.as_ref());
217 state.ck = t1;
218 t2
219 }
220
221 #[inline]
222 fn outbound_noise_act<T: secp256k1::Signing>(
223 secp_ctx: &Secp256k1<T>, state: &mut BidirectionalNoiseState, our_key: &SecretKey,
224 their_key: &PublicKey,
225 ) -> ([u8; 50], [u8; 32]) {
226 let our_pub = PublicKey::from_secret_key(secp_ctx, &our_key);
227
228 let mut sha = Sha256::engine();
229 sha.input(&state.h);
230 sha.input(&our_pub.serialize()[..]);
231 state.h = Sha256::from_engine(sha).to_byte_array();
232
233 let ss = SharedSecret::new(&their_key, &our_key);
234 let temp_k = PeerChannelEncryptor::hkdf(state, ss);
235
236 let mut res = [0; 50];
237 res[1..34].copy_from_slice(&our_pub.serialize()[..]);
238 PeerChannelEncryptor::encrypt_with_ad(&mut res[34..], 0, &temp_k, &state.h, &[0; 0]);
239
240 let mut sha = Sha256::engine();
241 sha.input(&state.h);
242 sha.input(&res[34..]);
243 state.h = Sha256::from_engine(sha).to_byte_array();
244
245 (res, temp_k)
246 }
247
248 #[inline]
249 fn inbound_noise_act<'a, 'b, NS: Deref>(
250 state: &mut BidirectionalNoiseState, act: &[u8], secret_key: NoiseSecretKey<'a, 'b, NS>,
251 ) -> Result<(PublicKey, [u8; 32]), LightningError>
252 where
253 NS::Target: NodeSigner,
254 {
255 assert_eq!(act.len(), 50);
256
257 if act[0] != 0 {
258 return Err(LightningError {
259 err: format!("Unknown handshake version number {}", act[0]),
260 action: msgs::ErrorAction::DisconnectPeer { msg: None },
261 });
262 }
263
264 let their_pub = match PublicKey::from_slice(&act[1..34]) {
265 Err(_) => {
266 return Err(LightningError {
267 err: format!("Invalid public key {}", &act[1..34].as_hex()),
268 action: msgs::ErrorAction::DisconnectPeer { msg: None },
269 })
270 },
271 Ok(key) => key,
272 };
273
274 let mut sha = Sha256::engine();
275 sha.input(&state.h);
276 sha.input(&their_pub.serialize()[..]);
277 state.h = Sha256::from_engine(sha).to_byte_array();
278
279 let ss = match secret_key {
280 NoiseSecretKey::InMemory(secret_key) => SharedSecret::new(&their_pub, secret_key),
281 NoiseSecretKey::NodeSigner(node_signer) => {
282 node_signer.ecdh(Recipient::Node, &their_pub, None).map_err(|_| LightningError {
283 err: "Failed to derive shared secret".to_owned(),
284 action: msgs::ErrorAction::DisconnectPeer { msg: None },
285 })?
286 },
287 };
288 let temp_k = PeerChannelEncryptor::hkdf(state, ss);
289
290 let mut dec = [0; 0];
291 PeerChannelEncryptor::decrypt_with_ad(&mut dec, 0, &temp_k, &state.h, &act[34..])?;
292
293 let mut sha = Sha256::engine();
294 sha.input(&state.h);
295 sha.input(&act[34..]);
296 state.h = Sha256::from_engine(sha).to_byte_array();
297
298 Ok((their_pub, temp_k))
299 }
300
301 pub fn get_act_one<C: secp256k1::Signing>(&mut self, secp_ctx: &Secp256k1<C>) -> [u8; 50] {
302 match self.noise_state {
303 NoiseState::InProgress {
304 ref mut state,
305 ref directional_state,
306 ref mut bidirectional_state,
307 } => match directional_state {
308 &DirectionalNoiseState::Outbound { ref ie } => {
309 if *state != NoiseStep::PreActOne {
310 panic!("Requested act at wrong step");
311 }
312
313 let (res, _) = PeerChannelEncryptor::outbound_noise_act(
314 secp_ctx,
315 bidirectional_state,
316 &ie,
317 &self.their_node_id.unwrap(),
318 );
319 *state = NoiseStep::PostActOne;
320 res
321 },
322 _ => panic!("Wrong direction for act"),
323 },
324 _ => panic!("Cannot get act one after noise handshake completes"),
325 }
326 }
327
328 pub fn process_act_one_with_keys<C: secp256k1::Signing, NS: Deref>(
329 &mut self, act_one: &[u8], node_signer: &NS, our_ephemeral: SecretKey,
330 secp_ctx: &Secp256k1<C>,
331 ) -> Result<[u8; 50], LightningError>
332 where
333 NS::Target: NodeSigner,
334 {
335 assert_eq!(act_one.len(), 50);
336
337 match self.noise_state {
338 NoiseState::InProgress {
339 ref mut state,
340 ref mut directional_state,
341 ref mut bidirectional_state,
342 } => match directional_state {
343 &mut DirectionalNoiseState::Inbound { ref mut ie, ref mut re, ref mut temp_k2 } => {
344 if *state != NoiseStep::PreActOne {
345 panic!("Requested act at wrong step");
346 }
347
348 let (their_pub, _) = PeerChannelEncryptor::inbound_noise_act(
349 bidirectional_state,
350 act_one,
351 NoiseSecretKey::NodeSigner(node_signer),
352 )?;
353 ie.get_or_insert(their_pub);
354
355 re.get_or_insert(our_ephemeral);
356
357 let (res, temp_k) = PeerChannelEncryptor::outbound_noise_act(
358 secp_ctx,
359 bidirectional_state,
360 &re.unwrap(),
361 &ie.unwrap(),
362 );
363 *temp_k2 = Some(temp_k);
364 *state = NoiseStep::PostActTwo;
365 Ok(res)
366 },
367 _ => panic!("Wrong direction for act"),
368 },
369 _ => panic!("Cannot get act one after noise handshake completes"),
370 }
371 }
372
373 pub fn process_act_two<NS: Deref>(
374 &mut self, act_two: &[u8], node_signer: &NS,
375 ) -> Result<([u8; 66], PublicKey), LightningError>
376 where
377 NS::Target: NodeSigner,
378 {
379 assert_eq!(act_two.len(), 50);
380
381 let final_hkdf;
382 let ck;
383 let res: [u8; 66] = match self.noise_state {
384 NoiseState::InProgress {
385 ref state,
386 ref directional_state,
387 ref mut bidirectional_state,
388 } => match directional_state {
389 &DirectionalNoiseState::Outbound { ref ie } => {
390 if *state != NoiseStep::PostActOne {
391 panic!("Requested act at wrong step");
392 }
393
394 let (re, temp_k2) = PeerChannelEncryptor::inbound_noise_act(
395 bidirectional_state,
396 act_two,
397 NoiseSecretKey::<NS>::InMemory(&ie),
398 )?;
399
400 let mut res = [0; 66];
401 let our_node_id =
402 node_signer.get_node_id(Recipient::Node).map_err(|_| LightningError {
403 err: "Failed to encrypt message".to_owned(),
404 action: msgs::ErrorAction::DisconnectPeer { msg: None },
405 })?;
406
407 PeerChannelEncryptor::encrypt_with_ad(
408 &mut res[1..50],
409 1,
410 &temp_k2,
411 &bidirectional_state.h,
412 &our_node_id.serialize()[..],
413 );
414
415 let mut sha = Sha256::engine();
416 sha.input(&bidirectional_state.h);
417 sha.input(&res[1..50]);
418 bidirectional_state.h = Sha256::from_engine(sha).to_byte_array();
419
420 let ss = node_signer.ecdh(Recipient::Node, &re, None).map_err(|_| {
421 LightningError {
422 err: "Failed to derive shared secret".to_owned(),
423 action: msgs::ErrorAction::DisconnectPeer { msg: None },
424 }
425 })?;
426 let temp_k = PeerChannelEncryptor::hkdf(bidirectional_state, ss);
427
428 PeerChannelEncryptor::encrypt_with_ad(
429 &mut res[50..],
430 0,
431 &temp_k,
432 &bidirectional_state.h,
433 &[0; 0],
434 );
435 final_hkdf = hkdf_extract_expand_twice(&bidirectional_state.ck, &[0; 0]);
436 ck = bidirectional_state.ck.clone();
437 res
438 },
439 _ => panic!("Wrong direction for act"),
440 },
441 _ => panic!("Cannot get act one after noise handshake completes"),
442 };
443
444 let (sk, rk) = final_hkdf;
445 self.noise_state = NoiseState::Finished { sk, sn: 0, sck: ck.clone(), rk, rn: 0, rck: ck };
446
447 Ok((res, self.their_node_id.unwrap().clone()))
448 }
449
450 pub fn process_act_three(&mut self, act_three: &[u8]) -> Result<PublicKey, LightningError> {
451 assert_eq!(act_three.len(), 66);
452
453 let final_hkdf;
454 let ck;
455 match self.noise_state {
456 NoiseState::InProgress {
457 ref state,
458 ref directional_state,
459 ref mut bidirectional_state,
460 } => match directional_state {
461 &DirectionalNoiseState::Inbound { ie: _, ref re, ref temp_k2 } => {
462 if *state != NoiseStep::PostActTwo {
463 panic!("Requested act at wrong step");
464 }
465 if act_three[0] != 0 {
466 return Err(LightningError {
467 err: format!("Unknown handshake version number {}", act_three[0]),
468 action: msgs::ErrorAction::DisconnectPeer { msg: None },
469 });
470 }
471
472 let mut their_node_id = [0; 33];
473 PeerChannelEncryptor::decrypt_with_ad(
474 &mut their_node_id,
475 1,
476 &temp_k2.unwrap(),
477 &bidirectional_state.h,
478 &act_three[1..50],
479 )?;
480 self.their_node_id = Some(match PublicKey::from_slice(&their_node_id) {
481 Ok(key) => key,
482 Err(_) => {
483 return Err(LightningError {
484 err: format!("Bad node_id from peer, {}", &their_node_id.as_hex()),
485 action: msgs::ErrorAction::DisconnectPeer { msg: None },
486 })
487 },
488 });
489
490 let mut sha = Sha256::engine();
491 sha.input(&bidirectional_state.h);
492 sha.input(&act_three[1..50]);
493 bidirectional_state.h = Sha256::from_engine(sha).to_byte_array();
494
495 let ss = SharedSecret::new(&self.their_node_id.unwrap(), &re.unwrap());
496 let temp_k = PeerChannelEncryptor::hkdf(bidirectional_state, ss);
497
498 PeerChannelEncryptor::decrypt_with_ad(
499 &mut [0; 0],
500 0,
501 &temp_k,
502 &bidirectional_state.h,
503 &act_three[50..],
504 )?;
505 final_hkdf = hkdf_extract_expand_twice(&bidirectional_state.ck, &[0; 0]);
506 ck = bidirectional_state.ck.clone();
507 },
508 _ => panic!("Wrong direction for act"),
509 },
510 _ => panic!("Cannot get act one after noise handshake completes"),
511 }
512
513 let (rk, sk) = final_hkdf;
514 self.noise_state = NoiseState::Finished { sk, sn: 0, sck: ck.clone(), rk, rn: 0, rck: ck };
515
516 Ok(self.their_node_id.unwrap().clone())
517 }
518
519 fn encrypt_message_with_header_0s(&mut self, msgbuf: &mut Vec<u8>) {
528 let msg_len = msgbuf.len() - 16 - 2;
529 if msg_len > LN_MAX_MSG_LEN {
530 panic!("Attempted to encrypt message longer than 65535 bytes!");
531 }
532
533 match self.noise_state {
534 NoiseState::Finished { ref mut sk, ref mut sn, ref mut sck, rk: _, rn: _, rck: _ } => {
535 if *sn >= 1000 {
536 let (new_sck, new_sk) = hkdf_extract_expand_twice(sck, sk);
537 *sck = new_sck;
538 *sk = new_sk;
539 *sn = 0;
540 }
541
542 Self::encrypt_with_ad(
543 &mut msgbuf[0..16 + 2],
544 *sn,
545 sk,
546 &[0; 0],
547 &(msg_len as u16).to_be_bytes(),
548 );
549 *sn += 1;
550
551 Self::encrypt_in_place_with_ad(msgbuf, 16 + 2, *sn, sk, &[0; 0]);
552 *sn += 1;
553 },
554 _ => panic!("Tried to encrypt a message prior to noise handshake completion"),
555 }
556 }
557
558 pub fn encrypt_buffer(&mut self, mut msg: MessageBuf) -> Vec<u8> {
561 self.encrypt_message_with_header_0s(&mut msg.0);
562 msg.0
563 }
564
565 pub fn encrypt_message<M: wire::Type>(&mut self, message: &M) -> Vec<u8> {
569 let mut res = VecWriter(Vec::with_capacity(MSG_BUF_ALLOC_SIZE));
572 res.0.resize(16 + 2, 0);
573 wire::write(message, &mut res).expect("In-memory messages must never fail to serialize");
574
575 self.encrypt_message_with_header_0s(&mut res.0);
576 res.0
577 }
578
579 pub fn decrypt_length_header(&mut self, msg: &[u8]) -> Result<u16, LightningError> {
582 assert_eq!(msg.len(), 16 + 2);
583
584 match self.noise_state {
585 NoiseState::Finished { sk: _, sn: _, sck: _, ref mut rk, ref mut rn, ref mut rck } => {
586 if *rn >= 1000 {
587 let (new_rck, new_rk) = hkdf_extract_expand_twice(rck, rk);
588 *rck = new_rck;
589 *rk = new_rk;
590 *rn = 0;
591 }
592
593 let mut res = [0; 2];
594 Self::decrypt_with_ad(&mut res, *rn, rk, &[0; 0], msg)?;
595 *rn += 1;
596 Ok(u16::from_be_bytes(res))
597 },
598 _ => panic!("Tried to decrypt a message prior to noise handshake completion"),
599 }
600 }
601
602 pub fn decrypt_message(&mut self, msg: &mut [u8]) -> Result<(), LightningError> {
607 if msg.len() > LN_MAX_MSG_LEN + 16 {
608 panic!("Attempted to decrypt message longer than 65535 + 16 bytes!");
609 }
610
611 match self.noise_state {
612 NoiseState::Finished { sk: _, sn: _, sck: _, ref rk, ref mut rn, rck: _ } => {
613 Self::decrypt_in_place_with_ad(&mut msg[..], *rn, rk, &[0; 0])?;
614 *rn += 1;
615 Ok(())
616 },
617 _ => panic!("Tried to decrypt a message prior to noise handshake completion"),
618 }
619 }
620
621 pub fn get_noise_step(&self) -> NextNoiseStep {
622 match self.noise_state {
623 NoiseState::InProgress { ref state, .. } => match state {
624 &NoiseStep::PreActOne => NextNoiseStep::ActOne,
625 &NoiseStep::PostActOne => NextNoiseStep::ActTwo,
626 &NoiseStep::PostActTwo => NextNoiseStep::ActThree,
627 },
628 NoiseState::Finished { .. } => NextNoiseStep::NoiseComplete,
629 }
630 }
631
632 pub fn is_ready_for_encryption(&self) -> bool {
633 match self.noise_state {
634 NoiseState::InProgress { .. } => false,
635 NoiseState::Finished { .. } => true,
636 }
637 }
638}
639
640pub struct MessageBuf(Vec<u8>);
643impl MessageBuf {
644 pub fn capacity(&self) -> usize {
646 self.0.capacity()
647 }
648
649 pub fn from_encoded(encoded_msg: &[u8]) -> Self {
654 if encoded_msg.len() > LN_MAX_MSG_LEN {
655 panic!("Attempted to encrypt message longer than 65535 bytes!");
656 }
657 let mut res = Vec::with_capacity(encoded_msg.len() + 16 * 2 + 2);
660 res.resize(encoded_msg.len() + 16 + 2, 0);
661 res[16 + 2..].copy_from_slice(&encoded_msg);
662 Self(res)
663 }
664
665 #[cfg(test)]
666 pub(crate) fn fetch_encoded_msg_with_type_pfx(&self) -> Vec<u8> {
667 self.0.clone().split_off(16 + 2)
668 }
669}
670
671#[cfg(test)]
672mod tests {
673 use super::{MessageBuf, LN_MAX_MSG_LEN};
674
675 use bitcoin::hex::FromHex;
676 use bitcoin::secp256k1::Secp256k1;
677 use bitcoin::secp256k1::{PublicKey, SecretKey};
678
679 use crate::ln::peer_channel_encryptor::{NoiseState, PeerChannelEncryptor};
680 use crate::util::test_utils::TestNodeSigner;
681
682 fn get_outbound_peer_for_initiator_test_vectors() -> PeerChannelEncryptor {
683 let hex = "028d7500dd4c12685d1f568b4c2b5048e8534b873319f3a8daa612b469132ec7f7";
684 let their_node_id = PublicKey::from_slice(&<Vec<u8>>::from_hex(hex).unwrap()[..]).unwrap();
685 let secp_ctx = Secp256k1::signing_only();
686
687 let hex = "1212121212121212121212121212121212121212121212121212121212121212";
688 let mut outbound_peer = PeerChannelEncryptor::new_outbound(
689 their_node_id,
690 SecretKey::from_slice(&<Vec<u8>>::from_hex(hex).unwrap()[..]).unwrap(),
691 );
692 let hex = "00036360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6a";
693 assert_eq!(outbound_peer.get_act_one(&secp_ctx)[..], <Vec<u8>>::from_hex(hex).unwrap()[..]);
694 outbound_peer
695 }
696
697 fn get_inbound_peer_for_test_vectors() -> PeerChannelEncryptor {
698 let hex = "2121212121212121212121212121212121212121212121212121212121212121";
700 let our_node_id = SecretKey::from_slice(&<Vec<u8>>::from_hex(hex).unwrap()[..]).unwrap();
701 let hex = "2222222222222222222222222222222222222222222222222222222222222222";
702 let our_ephemeral = SecretKey::from_slice(&<Vec<u8>>::from_hex(hex).unwrap()[..]).unwrap();
703 let secp_ctx = Secp256k1::new();
704 let node_signer = TestNodeSigner::new(our_node_id);
705
706 let mut inbound_peer = PeerChannelEncryptor::new_inbound(&&node_signer);
707
708 let hex = "00036360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6a";
709 let act_one = <Vec<u8>>::from_hex(hex).unwrap().to_vec();
710 let hex = "0002466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae";
711 assert_eq!(
712 inbound_peer
713 .process_act_one_with_keys(
714 &act_one[..],
715 &&node_signer,
716 our_ephemeral.clone(),
717 &secp_ctx
718 )
719 .unwrap()[..],
720 <Vec<u8>>::from_hex(hex).unwrap()[..]
721 );
722
723 let hex = "00b9e3a702e93e3a9948c2ed6e5fd7590a6e1c3a0344cfc9d5b57357049aa22355361aa02e55a8fc28fef5bd6d71ad0c38228dc68b1c466263b47fdf31e560e139ba";
724 let act_three = <Vec<u8>>::from_hex(hex).unwrap().to_vec();
725 let hex = "034f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa";
728 assert_eq!(
729 inbound_peer.process_act_three(&act_three[..]).unwrap().serialize()[..],
730 <Vec<u8>>::from_hex(hex).unwrap()[..]
731 );
732
733 match inbound_peer.noise_state {
734 NoiseState::Finished { sk, sn, sck, rk, rn, rck } => {
735 let hex = "bb9020b8965f4df047e07f955f3c4b88418984aadc5cdb35096b9ea8fa5c3442";
736 assert_eq!(sk, <Vec<u8>>::from_hex(hex).unwrap()[..]);
737 assert_eq!(sn, 0);
738 let hex = "919219dbb2920afa8db80f9a51787a840bcf111ed8d588caf9ab4be716e42b01";
739 assert_eq!(sck, <Vec<u8>>::from_hex(hex).unwrap()[..]);
740 let hex = "969ab31b4d288cedf6218839b27a3e2140827047f2c0f01bf5c04435d43511a9";
741 assert_eq!(rk, <Vec<u8>>::from_hex(hex).unwrap()[..]);
742 assert_eq!(rn, 0);
743 let hex = "919219dbb2920afa8db80f9a51787a840bcf111ed8d588caf9ab4be716e42b01";
744 assert_eq!(rck, <Vec<u8>>::from_hex(hex).unwrap()[..]);
745 },
746 _ => panic!(),
747 }
748
749 inbound_peer
750 }
751
752 #[test]
753 fn noise_initiator_test_vectors() {
754 let hex = "1111111111111111111111111111111111111111111111111111111111111111";
755 let our_node_id = SecretKey::from_slice(&<Vec<u8>>::from_hex(hex).unwrap()[..]).unwrap();
756 let node_signer = TestNodeSigner::new(our_node_id);
757
758 {
759 let mut outbound_peer = get_outbound_peer_for_initiator_test_vectors();
761
762 let hex = "0002466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae";
763 let act_two = <Vec<u8>>::from_hex(hex).unwrap().to_vec();
764 let hex = "00b9e3a702e93e3a9948c2ed6e5fd7590a6e1c3a0344cfc9d5b57357049aa22355361aa02e55a8fc28fef5bd6d71ad0c38228dc68b1c466263b47fdf31e560e139ba";
765 assert_eq!(
766 outbound_peer.process_act_two(&act_two[..], &&node_signer).unwrap().0[..],
767 <Vec<u8>>::from_hex(hex).unwrap()[..]
768 );
769
770 match outbound_peer.noise_state {
771 NoiseState::Finished { sk, sn, sck, rk, rn, rck } => {
772 let hex = "969ab31b4d288cedf6218839b27a3e2140827047f2c0f01bf5c04435d43511a9";
773 assert_eq!(sk, <Vec<u8>>::from_hex(hex).unwrap()[..]);
774 assert_eq!(sn, 0);
775 let hex = "919219dbb2920afa8db80f9a51787a840bcf111ed8d588caf9ab4be716e42b01";
776 assert_eq!(sck, <Vec<u8>>::from_hex(hex).unwrap()[..]);
777 let hex = "bb9020b8965f4df047e07f955f3c4b88418984aadc5cdb35096b9ea8fa5c3442";
778 assert_eq!(rk, <Vec<u8>>::from_hex(hex).unwrap()[..]);
779 assert_eq!(rn, 0);
780 let hex = "919219dbb2920afa8db80f9a51787a840bcf111ed8d588caf9ab4be716e42b01";
781 assert_eq!(rck, <Vec<u8>>::from_hex(hex).unwrap()[..]);
782 },
783 _ => panic!(),
784 }
785 }
786 {
787 }
790 {
791 let mut outbound_peer = get_outbound_peer_for_initiator_test_vectors();
793
794 let hex = "0102466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae";
795 let act_two = <Vec<u8>>::from_hex(hex).unwrap().to_vec();
796 assert!(outbound_peer.process_act_two(&act_two[..], &&node_signer).is_err());
797 }
798
799 {
800 let mut outbound_peer = get_outbound_peer_for_initiator_test_vectors();
802
803 let hex = "0004466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae";
804 let act_two = <Vec<u8>>::from_hex(hex).unwrap().to_vec();
805 assert!(outbound_peer.process_act_two(&act_two[..], &&node_signer).is_err());
806 }
807
808 {
809 let mut outbound_peer = get_outbound_peer_for_initiator_test_vectors();
811
812 let hex = "0002466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730af";
813 let act_two = <Vec<u8>>::from_hex(hex).unwrap().to_vec();
814 assert!(outbound_peer.process_act_two(&act_two[..], &&node_signer).is_err());
815 }
816 }
817
818 #[test]
819 fn noise_responder_test_vectors() {
820 let hex = "2121212121212121212121212121212121212121212121212121212121212121";
821 let our_node_id = SecretKey::from_slice(&<Vec<u8>>::from_hex(hex).unwrap()[..]).unwrap();
822 let hex = "2222222222222222222222222222222222222222222222222222222222222222";
823 let our_ephemeral = SecretKey::from_slice(&<Vec<u8>>::from_hex(hex).unwrap()[..]).unwrap();
824 let secp_ctx = Secp256k1::new();
825 let node_signer = TestNodeSigner::new(our_node_id);
826
827 {
828 let _ = get_inbound_peer_for_test_vectors();
829 }
830 {
831 }
834 {
835 let mut inbound_peer = PeerChannelEncryptor::new_inbound(&&node_signer);
837
838 let hex = "01036360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6a";
839 let act_one = <Vec<u8>>::from_hex(hex).unwrap().to_vec();
840 assert!(inbound_peer
841 .process_act_one_with_keys(
842 &act_one[..],
843 &&node_signer,
844 our_ephemeral.clone(),
845 &secp_ctx
846 )
847 .is_err());
848 }
849 {
850 let mut inbound_peer = PeerChannelEncryptor::new_inbound(&&node_signer);
852
853 let hex = "00046360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6a";
854 let act_one = <Vec<u8>>::from_hex(hex).unwrap().to_vec();
855 assert!(inbound_peer
856 .process_act_one_with_keys(
857 &act_one[..],
858 &&node_signer,
859 our_ephemeral.clone(),
860 &secp_ctx
861 )
862 .is_err());
863 }
864 {
865 let mut inbound_peer = PeerChannelEncryptor::new_inbound(&&node_signer);
867
868 let hex = "00036360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6b";
869 let act_one = <Vec<u8>>::from_hex(hex).unwrap().to_vec();
870 assert!(inbound_peer
871 .process_act_one_with_keys(
872 &act_one[..],
873 &&node_signer,
874 our_ephemeral.clone(),
875 &secp_ctx
876 )
877 .is_err());
878 }
879 {
880 let mut inbound_peer = PeerChannelEncryptor::new_inbound(&&node_signer);
882
883 let hex = "00036360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6a";
884 let act_one = <Vec<u8>>::from_hex(hex).unwrap().to_vec();
885 let hex = "0002466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae";
886 assert_eq!(
887 inbound_peer
888 .process_act_one_with_keys(
889 &act_one[..],
890 &&node_signer,
891 our_ephemeral.clone(),
892 &secp_ctx
893 )
894 .unwrap()[..],
895 <Vec<u8>>::from_hex(hex).unwrap()[..]
896 );
897
898 let hex = "01b9e3a702e93e3a9948c2ed6e5fd7590a6e1c3a0344cfc9d5b57357049aa22355361aa02e55a8fc28fef5bd6d71ad0c38228dc68b1c466263b47fdf31e560e139ba";
899 let act_three = <Vec<u8>>::from_hex(hex).unwrap().to_vec();
900 assert!(inbound_peer.process_act_three(&act_three[..]).is_err());
901 }
902 {
903 }
906 {
907 let mut inbound_peer = PeerChannelEncryptor::new_inbound(&&node_signer);
909
910 let hex = "00036360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6a";
911 let act_one = <Vec<u8>>::from_hex(hex).unwrap().to_vec();
912 let hex = "0002466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae";
913 assert_eq!(
914 inbound_peer
915 .process_act_one_with_keys(
916 &act_one[..],
917 &&node_signer,
918 our_ephemeral.clone(),
919 &secp_ctx
920 )
921 .unwrap()[..],
922 <Vec<u8>>::from_hex(hex).unwrap()[..]
923 );
924
925 let hex = "00c9e3a702e93e3a9948c2ed6e5fd7590a6e1c3a0344cfc9d5b57357049aa22355361aa02e55a8fc28fef5bd6d71ad0c38228dc68b1c466263b47fdf31e560e139ba";
926 let act_three = <Vec<u8>>::from_hex(hex).unwrap().to_vec();
927 assert!(inbound_peer.process_act_three(&act_three[..]).is_err());
928 }
929 {
930 let mut inbound_peer = PeerChannelEncryptor::new_inbound(&&node_signer);
932
933 let hex = "00036360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6a";
934 let act_one = <Vec<u8>>::from_hex(hex).unwrap().to_vec();
935 let hex = "0002466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae";
936 assert_eq!(
937 inbound_peer
938 .process_act_one_with_keys(
939 &act_one[..],
940 &&node_signer,
941 our_ephemeral.clone(),
942 &secp_ctx
943 )
944 .unwrap()[..],
945 <Vec<u8>>::from_hex(hex).unwrap()[..]
946 );
947
948 let hex = "00bfe3a702e93e3a9948c2ed6e5fd7590a6e1c3a0344cfc9d5b57357049aa2235536ad09a8ee351870c2bb7f78b754a26c6cef79a98d25139c856d7efd252c2ae73c";
949 let act_three = <Vec<u8>>::from_hex(hex).unwrap().to_vec();
950 assert!(inbound_peer.process_act_three(&act_three[..]).is_err());
951 }
952 {
953 let mut inbound_peer = PeerChannelEncryptor::new_inbound(&&node_signer);
955
956 let hex = "00036360e856310ce5d294e8be33fc807077dc56ac80d95d9cd4ddbd21325eff73f70df6086551151f58b8afe6c195782c6a";
957 let act_one = <Vec<u8>>::from_hex(hex).unwrap().to_vec();
958 let hex = "0002466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae";
959 assert_eq!(
960 inbound_peer
961 .process_act_one_with_keys(
962 &act_one[..],
963 &&node_signer,
964 our_ephemeral.clone(),
965 &secp_ctx
966 )
967 .unwrap()[..],
968 <Vec<u8>>::from_hex(hex).unwrap()[..]
969 );
970
971 let hex = "00b9e3a702e93e3a9948c2ed6e5fd7590a6e1c3a0344cfc9d5b57357049aa22355361aa02e55a8fc28fef5bd6d71ad0c38228dc68b1c466263b47fdf31e560e139bb";
972 let act_three = <Vec<u8>>::from_hex(hex).unwrap().to_vec();
973 assert!(inbound_peer.process_act_three(&act_three[..]).is_err());
974 }
975 }
976
977 #[test]
978 fn message_encryption_decryption_test_vectors() {
979 let mut outbound_peer = get_outbound_peer_for_initiator_test_vectors();
982
983 {
984 let hex = "1111111111111111111111111111111111111111111111111111111111111111";
985 let our_node_id =
986 SecretKey::from_slice(&<Vec<u8>>::from_hex(hex).unwrap()[..]).unwrap();
987 let node_signer = TestNodeSigner::new(our_node_id);
988
989 let hex = "0002466d7fcae563e5cb09a0d1870bb580344804617879a14949cf22285f1bae3f276e2470b93aac583c9ef6eafca3f730ae";
990 let act_two = <Vec<u8>>::from_hex(hex).unwrap().to_vec();
991 let hex = "00b9e3a702e93e3a9948c2ed6e5fd7590a6e1c3a0344cfc9d5b57357049aa22355361aa02e55a8fc28fef5bd6d71ad0c38228dc68b1c466263b47fdf31e560e139ba";
992 assert_eq!(
993 outbound_peer.process_act_two(&act_two[..], &&node_signer).unwrap().0[..],
994 <Vec<u8>>::from_hex(hex).unwrap()[..]
995 );
996
997 match outbound_peer.noise_state {
998 NoiseState::Finished { sk, sn, sck, rk, rn, rck } => {
999 let hex = "969ab31b4d288cedf6218839b27a3e2140827047f2c0f01bf5c04435d43511a9";
1000 assert_eq!(sk, <Vec<u8>>::from_hex(hex).unwrap()[..]);
1001 assert_eq!(sn, 0);
1002 let hex = "919219dbb2920afa8db80f9a51787a840bcf111ed8d588caf9ab4be716e42b01";
1003 assert_eq!(sck, <Vec<u8>>::from_hex(hex).unwrap()[..]);
1004 let hex = "bb9020b8965f4df047e07f955f3c4b88418984aadc5cdb35096b9ea8fa5c3442";
1005 assert_eq!(rk, <Vec<u8>>::from_hex(hex).unwrap()[..]);
1006 assert_eq!(rn, 0);
1007 let hex = "919219dbb2920afa8db80f9a51787a840bcf111ed8d588caf9ab4be716e42b01";
1008 assert_eq!(rck, <Vec<u8>>::from_hex(hex).unwrap()[..]);
1009 },
1010 _ => panic!(),
1011 }
1012 }
1013
1014 let mut inbound_peer = get_inbound_peer_for_test_vectors();
1015
1016 for i in 0..1005 {
1017 let msg = [0x68, 0x65, 0x6c, 0x6c, 0x6f];
1018 let mut res = outbound_peer.encrypt_buffer(MessageBuf::from_encoded(&msg));
1019 assert_eq!(res.len(), 5 + 2 * 16 + 2);
1020
1021 let len_header = res[0..2 + 16].to_vec();
1022 assert_eq!(
1023 inbound_peer.decrypt_length_header(&len_header[..]).unwrap() as usize,
1024 msg.len()
1025 );
1026
1027 if i == 0 {
1028 let hex = "cf2b30ddf0cf3f80e7c35a6e6730b59fe802473180f396d88a8fb0db8cbcf25d2f214cf9ea1d95";
1029 assert_eq!(res, <Vec<u8>>::from_hex(hex).unwrap());
1030 } else if i == 1 {
1031 let hex = "72887022101f0b6753e0c7de21657d35a4cb2a1f5cde2650528bbc8f837d0f0d7ad833b1a256a1";
1032 assert_eq!(res, <Vec<u8>>::from_hex(hex).unwrap());
1033 } else if i == 500 {
1034 let hex = "178cb9d7387190fa34db9c2d50027d21793c9bc2d40b1e14dcf30ebeeeb220f48364f7a4c68bf8";
1035 assert_eq!(res, <Vec<u8>>::from_hex(hex).unwrap());
1036 } else if i == 501 {
1037 let hex = "1b186c57d44eb6de4c057c49940d79bb838a145cb528d6e8fd26dbe50a60ca2c104b56b60e45bd";
1038 assert_eq!(res, <Vec<u8>>::from_hex(hex).unwrap());
1039 } else if i == 1000 {
1040 let hex = "4a2f3cc3b5e78ddb83dcb426d9863d9d9a723b0337c89dd0b005d89f8d3c05c52b76b29b740f09";
1041 assert_eq!(res, <Vec<u8>>::from_hex(hex).unwrap());
1042 } else if i == 1001 {
1043 let hex = "2ecd8c8a5629d0d02ab457a0fdd0f7b90a192cd46be5ecb6ca570bfc5e268338b1a16cf4ef2d36";
1044 assert_eq!(res, <Vec<u8>>::from_hex(hex).unwrap());
1045 }
1046
1047 inbound_peer.decrypt_message(&mut res[2 + 16..]).unwrap();
1048 assert_eq!(res[2 + 16..res.len() - 16], msg[..]);
1049 }
1050 }
1051
1052 #[test]
1053 fn max_msg_len_limit_value() {
1054 assert_eq!(LN_MAX_MSG_LEN, 65535);
1055 assert_eq!(LN_MAX_MSG_LEN, ::core::u16::MAX as usize);
1056 }
1057
1058 #[test]
1059 #[should_panic(expected = "Attempted to encrypt message longer than 65535 bytes!")]
1060 fn max_message_len_encryption() {
1061 let mut outbound_peer = get_outbound_peer_for_initiator_test_vectors();
1062 let msg = [4u8; LN_MAX_MSG_LEN + 1];
1063 outbound_peer.encrypt_buffer(MessageBuf::from_encoded(&msg));
1064 }
1065
1066 #[test]
1067 #[should_panic(expected = "Attempted to decrypt message longer than 65535 + 16 bytes!")]
1068 fn max_message_len_decryption() {
1069 let mut inbound_peer = get_inbound_peer_for_test_vectors();
1070
1071 let mut msg = [4u8; LN_MAX_MSG_LEN + 17];
1073 inbound_peer.decrypt_message(&mut msg).unwrap();
1074 }
1075}