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