Track block hash, return via `get_relevant_txids`
[rust-lightning] / lightning / src / onion_message / blinded_route.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 //! Creating blinded routes and related utilities live here.
11
12 use bitcoin::hashes::{Hash, HashEngine};
13 use bitcoin::hashes::sha256::Hash as Sha256;
14 use bitcoin::secp256k1::{self, PublicKey, Scalar, Secp256k1, SecretKey};
15
16 use crate::chain::keysinterface::{KeysInterface, Recipient};
17 use super::packet::ControlTlvs;
18 use super::utils;
19 use crate::ln::msgs::DecodeError;
20 use crate::ln::onion_utils;
21 use crate::util::chacha20poly1305rfc::{ChaChaPolyReadAdapter, ChaChaPolyWriteAdapter};
22 use crate::util::ser::{FixedLengthReader, LengthReadableArgs, Readable, VecWriter, Writeable, Writer};
23
24 use core::mem;
25 use core::ops::Deref;
26 use crate::io::{self, Cursor};
27 use crate::prelude::*;
28
29 /// Onion messages can be sent and received to blinded routes, which serve to hide the identity of
30 /// the recipient.
31 pub struct BlindedRoute {
32         /// To send to a blinded route, the sender first finds a route to the unblinded
33         /// `introduction_node_id`, which can unblind its [`encrypted_payload`] to find out the onion
34         /// message's next hop and forward it along.
35         ///
36         /// [`encrypted_payload`]: BlindedHop::encrypted_payload
37         pub(super) introduction_node_id: PublicKey,
38         /// Used by the introduction node to decrypt its [`encrypted_payload`] to forward the onion
39         /// message.
40         ///
41         /// [`encrypted_payload`]: BlindedHop::encrypted_payload
42         pub(super) blinding_point: PublicKey,
43         /// The hops composing the blinded route.
44         pub(super) blinded_hops: Vec<BlindedHop>,
45 }
46
47 /// Used to construct the blinded hops portion of a blinded route. These hops cannot be identified
48 /// by outside observers and thus can be used to hide the identity of the recipient.
49 pub struct BlindedHop {
50         /// The blinded node id of this hop in a blinded route.
51         pub(super) blinded_node_id: PublicKey,
52         /// The encrypted payload intended for this hop in a blinded route.
53         // The node sending to this blinded route will later encode this payload into the onion packet for
54         // this hop.
55         pub(super) encrypted_payload: Vec<u8>,
56 }
57
58 impl BlindedRoute {
59         /// Create a blinded route to be forwarded along `node_pks`. The last node pubkey in `node_pks`
60         /// will be the destination node.
61         ///
62         /// Errors if less than two hops are provided or if `node_pk`(s) are invalid.
63         //  TODO: make all payloads the same size with padding + add dummy hops
64         pub fn new<K: KeysInterface, T: secp256k1::Signing + secp256k1::Verification>
65                 (node_pks: &[PublicKey], keys_manager: &K, secp_ctx: &Secp256k1<T>) -> Result<Self, ()>
66         {
67                 if node_pks.len() < 2 { return Err(()) }
68                 let blinding_secret_bytes = keys_manager.get_secure_random_bytes();
69                 let blinding_secret = SecretKey::from_slice(&blinding_secret_bytes[..]).expect("RNG is busted");
70                 let introduction_node_id = node_pks[0];
71
72                 Ok(BlindedRoute {
73                         introduction_node_id,
74                         blinding_point: PublicKey::from_secret_key(secp_ctx, &blinding_secret),
75                         blinded_hops: blinded_hops(secp_ctx, node_pks, &blinding_secret).map_err(|_| ())?,
76                 })
77         }
78
79         // Advance the blinded route by one hop, so make the second hop into the new introduction node.
80         pub(super) fn advance_by_one<K: Deref, T: secp256k1::Signing + secp256k1::Verification>
81                 (&mut self, keys_manager: &K, secp_ctx: &Secp256k1<T>) -> Result<(), ()>
82                 where K::Target: KeysInterface
83         {
84                 let control_tlvs_ss = keys_manager.ecdh(Recipient::Node, &self.blinding_point, None)?;
85                 let rho = onion_utils::gen_rho_from_shared_secret(&control_tlvs_ss.secret_bytes());
86                 let encrypted_control_tlvs = self.blinded_hops.remove(0).encrypted_payload;
87                 let mut s = Cursor::new(&encrypted_control_tlvs);
88                 let mut reader = FixedLengthReader::new(&mut s, encrypted_control_tlvs.len() as u64);
89                 match ChaChaPolyReadAdapter::read(&mut reader, rho) {
90                         Ok(ChaChaPolyReadAdapter { readable: ControlTlvs::Forward(ForwardTlvs {
91                                 mut next_node_id, next_blinding_override,
92                         })}) => {
93                                 let mut new_blinding_point = match next_blinding_override {
94                                         Some(blinding_point) => blinding_point,
95                                         None => {
96                                                 let blinding_factor = {
97                                                         let mut sha = Sha256::engine();
98                                                         sha.input(&self.blinding_point.serialize()[..]);
99                                                         sha.input(control_tlvs_ss.as_ref());
100                                                         Sha256::from_engine(sha).into_inner()
101                                                 };
102                                                 self.blinding_point.mul_tweak(secp_ctx, &Scalar::from_be_bytes(blinding_factor).unwrap())
103                                                         .map_err(|_| ())?
104                                         }
105                                 };
106                                 mem::swap(&mut self.blinding_point, &mut new_blinding_point);
107                                 mem::swap(&mut self.introduction_node_id, &mut next_node_id);
108                                 Ok(())
109                         },
110                         _ => Err(())
111                 }
112         }
113 }
114
115 /// Construct blinded hops for the given `unblinded_path`.
116 fn blinded_hops<T: secp256k1::Signing + secp256k1::Verification>(
117         secp_ctx: &Secp256k1<T>, unblinded_path: &[PublicKey], session_priv: &SecretKey
118 ) -> Result<Vec<BlindedHop>, secp256k1::Error> {
119         let mut blinded_hops = Vec::with_capacity(unblinded_path.len());
120
121         let mut prev_ss_and_blinded_node_id = None;
122         utils::construct_keys_callback(secp_ctx, unblinded_path, None, session_priv, |blinded_node_id, _, _, encrypted_payload_ss, unblinded_pk, _| {
123                 if let Some((prev_ss, prev_blinded_node_id)) = prev_ss_and_blinded_node_id {
124                         if let Some(pk) = unblinded_pk {
125                                 let payload = ForwardTlvs {
126                                         next_node_id: pk,
127                                         next_blinding_override: None,
128                                 };
129                                 blinded_hops.push(BlindedHop {
130                                         blinded_node_id: prev_blinded_node_id,
131                                         encrypted_payload: encrypt_payload(payload, prev_ss),
132                                 });
133                         } else { debug_assert!(false); }
134                 }
135                 prev_ss_and_blinded_node_id = Some((encrypted_payload_ss, blinded_node_id));
136         })?;
137
138         if let Some((final_ss, final_blinded_node_id)) = prev_ss_and_blinded_node_id {
139                 let final_payload = ReceiveTlvs { path_id: None };
140                 blinded_hops.push(BlindedHop {
141                         blinded_node_id: final_blinded_node_id,
142                         encrypted_payload: encrypt_payload(final_payload, final_ss),
143                 });
144         } else { debug_assert!(false) }
145
146         Ok(blinded_hops)
147 }
148
149 /// Encrypt TLV payload to be used as a [`BlindedHop::encrypted_payload`].
150 fn encrypt_payload<P: Writeable>(payload: P, encrypted_tlvs_ss: [u8; 32]) -> Vec<u8> {
151         let mut writer = VecWriter(Vec::new());
152         let write_adapter = ChaChaPolyWriteAdapter::new(encrypted_tlvs_ss, &payload);
153         write_adapter.write(&mut writer).expect("In-memory writes cannot fail");
154         writer.0
155 }
156
157 impl Writeable for BlindedRoute {
158         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
159                 self.introduction_node_id.write(w)?;
160                 self.blinding_point.write(w)?;
161                 (self.blinded_hops.len() as u8).write(w)?;
162                 for hop in &self.blinded_hops {
163                         hop.write(w)?;
164                 }
165                 Ok(())
166         }
167 }
168
169 impl Readable for BlindedRoute {
170         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
171                 let introduction_node_id = Readable::read(r)?;
172                 let blinding_point = Readable::read(r)?;
173                 let num_hops: u8 = Readable::read(r)?;
174                 if num_hops == 0 { return Err(DecodeError::InvalidValue) }
175                 let mut blinded_hops: Vec<BlindedHop> = Vec::with_capacity(num_hops.into());
176                 for _ in 0..num_hops {
177                         blinded_hops.push(Readable::read(r)?);
178                 }
179                 Ok(BlindedRoute {
180                         introduction_node_id,
181                         blinding_point,
182                         blinded_hops,
183                 })
184         }
185 }
186
187 impl_writeable!(BlindedHop, {
188         blinded_node_id,
189         encrypted_payload
190 });
191
192 /// TLVs to encode in an intermediate onion message packet's hop data. When provided in a blinded
193 /// route, they are encoded into [`BlindedHop::encrypted_payload`].
194 pub(crate) struct ForwardTlvs {
195         /// The node id of the next hop in the onion message's path.
196         pub(super) next_node_id: PublicKey,
197         /// Senders to a blinded route use this value to concatenate the route they find to the
198         /// introduction node with the blinded route.
199         pub(super) next_blinding_override: Option<PublicKey>,
200 }
201
202 /// Similar to [`ForwardTlvs`], but these TLVs are for the final node.
203 pub(crate) struct ReceiveTlvs {
204         /// If `path_id` is `Some`, it is used to identify the blinded route that this onion message is
205         /// sending to. This is useful for receivers to check that said blinded route is being used in
206         /// the right context.
207         pub(super) path_id: Option<[u8; 32]>,
208 }
209
210 impl Writeable for ForwardTlvs {
211         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
212                 // TODO: write padding
213                 encode_tlv_stream!(writer, {
214                         (4, self.next_node_id, required),
215                         (8, self.next_blinding_override, option)
216                 });
217                 Ok(())
218         }
219 }
220
221 impl Writeable for ReceiveTlvs {
222         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
223                 // TODO: write padding
224                 encode_tlv_stream!(writer, {
225                         (6, self.path_id, option),
226                 });
227                 Ok(())
228         }
229 }