a188274a5d2fccd0b2eeee67c77c16530c53e1aa
[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::msgs::DecodeError;
20 use crate::ln::onion_utils;
21 use crate::onion_message::Destination;
22 use crate::util::chacha20poly1305rfc::ChaChaPolyWriteAdapter;
23 use crate::util::ser::{Readable, VecWriter, Writeable};
24
25 use crate::io;
26 use crate::prelude::*;
27
28 // TODO: DRY with onion_utils::construct_onion_keys_callback
29 #[inline]
30 pub(crate) fn construct_keys_callback<T: secp256k1::Signing + secp256k1::Verification,
31         FType: FnMut(PublicKey, SharedSecret, PublicKey, [u8; 32], Option<PublicKey>, Option<Vec<u8>>)>(
32         secp_ctx: &Secp256k1<T>, unblinded_path: &[PublicKey], destination: Option<Destination>,
33         session_priv: &SecretKey, mut callback: FType
34 ) -> Result<(), secp256k1::Error> {
35         let mut msg_blinding_point_priv = session_priv.clone();
36         let mut msg_blinding_point = PublicKey::from_secret_key(secp_ctx, &msg_blinding_point_priv);
37         let mut onion_packet_pubkey_priv = msg_blinding_point_priv.clone();
38         let mut onion_packet_pubkey = msg_blinding_point.clone();
39
40         macro_rules! build_keys {
41                 ($pk: expr, $blinded: expr, $encrypted_payload: expr) => {{
42                         let encrypted_data_ss = SharedSecret::new(&$pk, &msg_blinding_point_priv);
43
44                         let blinded_hop_pk = if $blinded { $pk } else {
45                                 let hop_pk_blinding_factor = {
46                                         let mut hmac = HmacEngine::<Sha256>::new(b"blinded_node_id");
47                                         hmac.input(encrypted_data_ss.as_ref());
48                                         Hmac::from_engine(hmac).into_inner()
49                                 };
50                                 $pk.mul_tweak(secp_ctx, &Scalar::from_be_bytes(hop_pk_blinding_factor).unwrap())?
51                         };
52                         let onion_packet_ss = SharedSecret::new(&blinded_hop_pk, &onion_packet_pubkey_priv);
53
54                         let rho = onion_utils::gen_rho_from_shared_secret(encrypted_data_ss.as_ref());
55                         let unblinded_pk_opt = if $blinded { None } else { Some($pk) };
56                         callback(blinded_hop_pk, onion_packet_ss, onion_packet_pubkey, rho, unblinded_pk_opt, $encrypted_payload);
57                         (encrypted_data_ss, onion_packet_ss)
58                 }}
59         }
60
61         macro_rules! build_keys_in_loop {
62                 ($pk: expr, $blinded: expr, $encrypted_payload: expr) => {
63                         let (encrypted_data_ss, onion_packet_ss) = build_keys!($pk, $blinded, $encrypted_payload);
64
65                         let msg_blinding_point_blinding_factor = {
66                                 let mut sha = Sha256::engine();
67                                 sha.input(&msg_blinding_point.serialize()[..]);
68                                 sha.input(encrypted_data_ss.as_ref());
69                                 Sha256::from_engine(sha).into_inner()
70                         };
71
72                         msg_blinding_point_priv = msg_blinding_point_priv.mul_tweak(&Scalar::from_be_bytes(msg_blinding_point_blinding_factor).unwrap())?;
73                         msg_blinding_point = PublicKey::from_secret_key(secp_ctx, &msg_blinding_point_priv);
74
75                         let onion_packet_pubkey_blinding_factor = {
76                                 let mut sha = Sha256::engine();
77                                 sha.input(&onion_packet_pubkey.serialize()[..]);
78                                 sha.input(onion_packet_ss.as_ref());
79                                 Sha256::from_engine(sha).into_inner()
80                         };
81                         onion_packet_pubkey_priv = onion_packet_pubkey_priv.mul_tweak(&Scalar::from_be_bytes(onion_packet_pubkey_blinding_factor).unwrap())?;
82                         onion_packet_pubkey = PublicKey::from_secret_key(secp_ctx, &onion_packet_pubkey_priv);
83                 };
84         }
85
86         for pk in unblinded_path {
87                 build_keys_in_loop!(*pk, false, None);
88         }
89         if let Some(dest) = destination {
90                 match dest {
91                         Destination::Node(pk) => {
92                                 build_keys!(pk, false, None);
93                         },
94                         Destination::BlindedPath(BlindedPath { blinded_hops, .. }) => {
95                                 for hop in blinded_hops {
96                                         build_keys_in_loop!(hop.blinded_node_id, true, Some(hop.encrypted_payload));
97                                 }
98                         },
99                 }
100         }
101         Ok(())
102 }
103
104 /// Encrypt TLV payload to be used as a [`crate::blinded_path::BlindedHop::encrypted_payload`].
105 pub(super) fn encrypt_payload<P: Writeable>(payload: P, encrypted_tlvs_ss: [u8; 32]) -> Vec<u8> {
106         let mut writer = VecWriter(Vec::new());
107         let write_adapter = ChaChaPolyWriteAdapter::new(encrypted_tlvs_ss, &payload);
108         write_adapter.write(&mut writer).expect("In-memory writes cannot fail");
109         writer.0
110 }
111
112 /// Blinded path encrypted payloads may be padded to ensure they are equal length.
113 ///
114 /// Reads padding to the end, ignoring what's read.
115 pub(crate) struct Padding {}
116 impl Readable for Padding {
117         #[inline]
118         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
119                 loop {
120                         let mut buf = [0; 8192];
121                         if reader.read(&mut buf[..])? == 0 { break; }
122                 }
123                 Ok(Self {})
124         }
125 }