c1ecff4b4af19155211fba89920b3852e8b22be1
[rust-lightning] / lightning / src / blinded_path / utils.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 //! Onion message utility methods live here.
11
12 use bitcoin::hashes::{Hash, HashEngine};
13 use bitcoin::hashes::hmac::{Hmac, HmacEngine};
14 use bitcoin::hashes::sha256::Hash as Sha256;
15 use bitcoin::secp256k1::{self, PublicKey, Secp256k1, SecretKey, Scalar};
16 use bitcoin::secp256k1::ecdh::SharedSecret;
17
18 use super::BlindedPath;
19 use crate::ln::onion_utils;
20 use crate::onion_message::Destination;
21 use crate::util::chacha20poly1305rfc::ChaChaPolyWriteAdapter;
22 use crate::util::ser::{VecWriter, Writeable};
23
24 use crate::prelude::*;
25
26 // TODO: DRY with onion_utils::construct_onion_keys_callback
27 #[inline]
28 pub(crate) fn construct_keys_callback<T: secp256k1::Signing + secp256k1::Verification,
29         FType: FnMut(PublicKey, SharedSecret, PublicKey, [u8; 32], Option<PublicKey>, Option<Vec<u8>>)>(
30         secp_ctx: &Secp256k1<T>, unblinded_path: &[PublicKey], destination: Option<Destination>,
31         session_priv: &SecretKey, mut callback: FType
32 ) -> Result<(), secp256k1::Error> {
33         let mut msg_blinding_point_priv = session_priv.clone();
34         let mut msg_blinding_point = PublicKey::from_secret_key(secp_ctx, &msg_blinding_point_priv);
35         let mut onion_packet_pubkey_priv = msg_blinding_point_priv.clone();
36         let mut onion_packet_pubkey = msg_blinding_point.clone();
37
38         macro_rules! build_keys {
39                 ($pk: expr, $blinded: expr, $encrypted_payload: expr) => {{
40                         let encrypted_data_ss = SharedSecret::new(&$pk, &msg_blinding_point_priv);
41
42                         let blinded_hop_pk = if $blinded { $pk } else {
43                                 let hop_pk_blinding_factor = {
44                                         let mut hmac = HmacEngine::<Sha256>::new(b"blinded_node_id");
45                                         hmac.input(encrypted_data_ss.as_ref());
46                                         Hmac::from_engine(hmac).into_inner()
47                                 };
48                                 $pk.mul_tweak(secp_ctx, &Scalar::from_be_bytes(hop_pk_blinding_factor).unwrap())?
49                         };
50                         let onion_packet_ss = SharedSecret::new(&blinded_hop_pk, &onion_packet_pubkey_priv);
51
52                         let rho = onion_utils::gen_rho_from_shared_secret(encrypted_data_ss.as_ref());
53                         let unblinded_pk_opt = if $blinded { None } else { Some($pk) };
54                         callback(blinded_hop_pk, onion_packet_ss, onion_packet_pubkey, rho, unblinded_pk_opt, $encrypted_payload);
55                         (encrypted_data_ss, onion_packet_ss)
56                 }}
57         }
58
59         macro_rules! build_keys_in_loop {
60                 ($pk: expr, $blinded: expr, $encrypted_payload: expr) => {
61                         let (encrypted_data_ss, onion_packet_ss) = build_keys!($pk, $blinded, $encrypted_payload);
62
63                         let msg_blinding_point_blinding_factor = {
64                                 let mut sha = Sha256::engine();
65                                 sha.input(&msg_blinding_point.serialize()[..]);
66                                 sha.input(encrypted_data_ss.as_ref());
67                                 Sha256::from_engine(sha).into_inner()
68                         };
69
70                         msg_blinding_point_priv = msg_blinding_point_priv.mul_tweak(&Scalar::from_be_bytes(msg_blinding_point_blinding_factor).unwrap())?;
71                         msg_blinding_point = PublicKey::from_secret_key(secp_ctx, &msg_blinding_point_priv);
72
73                         let onion_packet_pubkey_blinding_factor = {
74                                 let mut sha = Sha256::engine();
75                                 sha.input(&onion_packet_pubkey.serialize()[..]);
76                                 sha.input(onion_packet_ss.as_ref());
77                                 Sha256::from_engine(sha).into_inner()
78                         };
79                         onion_packet_pubkey_priv = onion_packet_pubkey_priv.mul_tweak(&Scalar::from_be_bytes(onion_packet_pubkey_blinding_factor).unwrap())?;
80                         onion_packet_pubkey = PublicKey::from_secret_key(secp_ctx, &onion_packet_pubkey_priv);
81                 };
82         }
83
84         for pk in unblinded_path {
85                 build_keys_in_loop!(*pk, false, None);
86         }
87         if let Some(dest) = destination {
88                 match dest {
89                         Destination::Node(pk) => {
90                                 build_keys!(pk, false, None);
91                         },
92                         Destination::BlindedPath(BlindedPath { blinded_hops, .. }) => {
93                                 for hop in blinded_hops {
94                                         build_keys_in_loop!(hop.blinded_node_id, true, Some(hop.encrypted_payload));
95                                 }
96                         },
97                 }
98         }
99         Ok(())
100 }
101
102 /// Encrypt TLV payload to be used as a [`crate::blinded_path::BlindedHop::encrypted_payload`].
103 pub(super) fn encrypt_payload<P: Writeable>(payload: P, encrypted_tlvs_ss: [u8; 32]) -> Vec<u8> {
104         let mut writer = VecWriter(Vec::new());
105         let write_adapter = ChaChaPolyWriteAdapter::new(encrypted_tlvs_ss, &payload);
106         write_adapter.write(&mut writer).expect("In-memory writes cannot fail");
107         writer.0
108 }
109