Allow(unused_imports) on prelude imports
[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::{BlindedHop, BlindedPath};
19 use crate::ln::msgs::DecodeError;
20 use crate::ln::onion_utils;
21 use crate::onion_message::messenger::Destination;
22 use crate::crypto::streams::ChaChaPolyWriteAdapter;
23 use crate::util::ser::{Readable, Writeable};
24
25 use crate::io;
26
27 #[allow(unused_imports)]
28 use crate::prelude::*;
29
30 // TODO: DRY with onion_utils::construct_onion_keys_callback
31 #[inline]
32 pub(crate) fn construct_keys_callback<'a, T, I, F>(
33         secp_ctx: &Secp256k1<T>, unblinded_path: I, destination: Option<Destination>,
34         session_priv: &SecretKey, mut callback: F
35 ) -> Result<(), secp256k1::Error>
36 where
37         T: secp256k1::Signing + secp256k1::Verification,
38         I: Iterator<Item=&'a PublicKey>,
39         F: FnMut(PublicKey, SharedSecret, PublicKey, [u8; 32], Option<PublicKey>, Option<Vec<u8>>),
40 {
41         let mut msg_blinding_point_priv = session_priv.clone();
42         let mut msg_blinding_point = PublicKey::from_secret_key(secp_ctx, &msg_blinding_point_priv);
43         let mut onion_packet_pubkey_priv = msg_blinding_point_priv.clone();
44         let mut onion_packet_pubkey = msg_blinding_point.clone();
45
46         macro_rules! build_keys {
47                 ($pk: expr, $blinded: expr, $encrypted_payload: expr) => {{
48                         let encrypted_data_ss = SharedSecret::new(&$pk, &msg_blinding_point_priv);
49
50                         let blinded_hop_pk = if $blinded { $pk } else {
51                                 let hop_pk_blinding_factor = {
52                                         let mut hmac = HmacEngine::<Sha256>::new(b"blinded_node_id");
53                                         hmac.input(encrypted_data_ss.as_ref());
54                                         Hmac::from_engine(hmac).to_byte_array()
55                                 };
56                                 $pk.mul_tweak(secp_ctx, &Scalar::from_be_bytes(hop_pk_blinding_factor).unwrap())?
57                         };
58                         let onion_packet_ss = SharedSecret::new(&blinded_hop_pk, &onion_packet_pubkey_priv);
59
60                         let rho = onion_utils::gen_rho_from_shared_secret(encrypted_data_ss.as_ref());
61                         let unblinded_pk_opt = if $blinded { None } else { Some($pk) };
62                         callback(blinded_hop_pk, onion_packet_ss, onion_packet_pubkey, rho, unblinded_pk_opt, $encrypted_payload);
63                         (encrypted_data_ss, onion_packet_ss)
64                 }}
65         }
66
67         macro_rules! build_keys_in_loop {
68                 ($pk: expr, $blinded: expr, $encrypted_payload: expr) => {
69                         let (encrypted_data_ss, onion_packet_ss) = build_keys!($pk, $blinded, $encrypted_payload);
70
71                         let msg_blinding_point_blinding_factor = {
72                                 let mut sha = Sha256::engine();
73                                 sha.input(&msg_blinding_point.serialize()[..]);
74                                 sha.input(encrypted_data_ss.as_ref());
75                                 Sha256::from_engine(sha).to_byte_array()
76                         };
77
78                         msg_blinding_point_priv = msg_blinding_point_priv.mul_tweak(&Scalar::from_be_bytes(msg_blinding_point_blinding_factor).unwrap())?;
79                         msg_blinding_point = PublicKey::from_secret_key(secp_ctx, &msg_blinding_point_priv);
80
81                         let onion_packet_pubkey_blinding_factor = {
82                                 let mut sha = Sha256::engine();
83                                 sha.input(&onion_packet_pubkey.serialize()[..]);
84                                 sha.input(onion_packet_ss.as_ref());
85                                 Sha256::from_engine(sha).to_byte_array()
86                         };
87                         onion_packet_pubkey_priv = onion_packet_pubkey_priv.mul_tweak(&Scalar::from_be_bytes(onion_packet_pubkey_blinding_factor).unwrap())?;
88                         onion_packet_pubkey = PublicKey::from_secret_key(secp_ctx, &onion_packet_pubkey_priv);
89                 };
90         }
91
92         for pk in unblinded_path {
93                 build_keys_in_loop!(*pk, false, None);
94         }
95         if let Some(dest) = destination {
96                 match dest {
97                         Destination::Node(pk) => {
98                                 build_keys!(pk, false, None);
99                         },
100                         Destination::BlindedPath(BlindedPath { blinded_hops, .. }) => {
101                                 for hop in blinded_hops {
102                                         build_keys_in_loop!(hop.blinded_node_id, true, Some(hop.encrypted_payload));
103                                 }
104                         },
105                 }
106         }
107         Ok(())
108 }
109
110 // Panics if `unblinded_tlvs` length is less than `unblinded_pks` length
111 pub(super) fn construct_blinded_hops<'a, T, I1, I2>(
112         secp_ctx: &Secp256k1<T>, unblinded_pks: I1, mut unblinded_tlvs: I2, session_priv: &SecretKey
113 ) -> Result<Vec<BlindedHop>, secp256k1::Error>
114 where
115         T: secp256k1::Signing + secp256k1::Verification,
116         I1: Iterator<Item=&'a PublicKey>,
117         I2: Iterator,
118         I2::Item: Writeable
119 {
120         let mut blinded_hops = Vec::with_capacity(unblinded_pks.size_hint().0);
121         construct_keys_callback(
122                 secp_ctx, unblinded_pks, None, session_priv,
123                 |blinded_node_id, _, _, encrypted_payload_rho, _, _| {
124                         blinded_hops.push(BlindedHop {
125                                 blinded_node_id,
126                                 encrypted_payload: encrypt_payload(unblinded_tlvs.next().unwrap(), encrypted_payload_rho),
127                         });
128                 })?;
129         Ok(blinded_hops)
130 }
131
132 /// Encrypt TLV payload to be used as a [`crate::blinded_path::BlindedHop::encrypted_payload`].
133 fn encrypt_payload<P: Writeable>(payload: P, encrypted_tlvs_rho: [u8; 32]) -> Vec<u8> {
134         let write_adapter = ChaChaPolyWriteAdapter::new(encrypted_tlvs_rho, &payload);
135         write_adapter.encode()
136 }
137
138 /// Blinded path encrypted payloads may be padded to ensure they are equal length.
139 ///
140 /// Reads padding to the end, ignoring what's read.
141 pub(crate) struct Padding {}
142 impl Readable for Padding {
143         #[inline]
144         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
145                 loop {
146                         let mut buf = [0; 8192];
147                         if reader.read(&mut buf[..])? == 0 { break; }
148                 }
149                 Ok(Self {})
150         }
151 }