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