]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/blinded_path/mod.rs
Persist scorer upon update based on event handling
[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 and payments can be sent and received to blinded paths, which serve to hide the
31 /// identity of the recipient.
32 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
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 or payment'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 or payment.
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, Hash, PartialEq, Eq)]
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 for an onion message, to be forwarded along `node_pks`. The last node
63         /// pubkey in `node_pks` 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_for_message<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_message_hops(secp_ctx, node_pks, &blinding_secret).map_err(|_| ())?,
79                 })
80         }
81
82         // Advance the blinded onion message path by one hop, so make the second hop into the new
83         // introduction node.
84         pub(super) fn advance_message_path_by_one<NS: Deref, T: secp256k1::Signing + secp256k1::Verification>
85                 (&mut self, node_signer: &NS, secp_ctx: &Secp256k1<T>) -> Result<(), ()>
86                 where NS::Target: NodeSigner
87         {
88                 let control_tlvs_ss = node_signer.ecdh(Recipient::Node, &self.blinding_point, None)?;
89                 let rho = onion_utils::gen_rho_from_shared_secret(&control_tlvs_ss.secret_bytes());
90                 let encrypted_control_tlvs = self.blinded_hops.remove(0).encrypted_payload;
91                 let mut s = Cursor::new(&encrypted_control_tlvs);
92                 let mut reader = FixedLengthReader::new(&mut s, encrypted_control_tlvs.len() as u64);
93                 match ChaChaPolyReadAdapter::read(&mut reader, rho) {
94                         Ok(ChaChaPolyReadAdapter { readable: ControlTlvs::Forward(ForwardTlvs {
95                                 mut next_node_id, next_blinding_override,
96                         })}) => {
97                                 let mut new_blinding_point = match next_blinding_override {
98                                         Some(blinding_point) => blinding_point,
99                                         None => {
100                                                 let blinding_factor = {
101                                                         let mut sha = Sha256::engine();
102                                                         sha.input(&self.blinding_point.serialize()[..]);
103                                                         sha.input(control_tlvs_ss.as_ref());
104                                                         Sha256::from_engine(sha).into_inner()
105                                                 };
106                                                 self.blinding_point.mul_tweak(secp_ctx, &Scalar::from_be_bytes(blinding_factor).unwrap())
107                                                         .map_err(|_| ())?
108                                         }
109                                 };
110                                 mem::swap(&mut self.blinding_point, &mut new_blinding_point);
111                                 mem::swap(&mut self.introduction_node_id, &mut next_node_id);
112                                 Ok(())
113                         },
114                         _ => Err(())
115                 }
116         }
117 }
118
119 /// Construct blinded onion message hops for the given `unblinded_path`.
120 fn blinded_message_hops<T: secp256k1::Signing + secp256k1::Verification>(
121         secp_ctx: &Secp256k1<T>, unblinded_path: &[PublicKey], session_priv: &SecretKey
122 ) -> Result<Vec<BlindedHop>, secp256k1::Error> {
123         let mut blinded_hops = Vec::with_capacity(unblinded_path.len());
124
125         let mut prev_ss_and_blinded_node_id = None;
126         utils::construct_keys_callback(secp_ctx, unblinded_path, None, session_priv, |blinded_node_id, _, _, encrypted_payload_ss, unblinded_pk, _| {
127                 if let Some((prev_ss, prev_blinded_node_id)) = prev_ss_and_blinded_node_id {
128                         if let Some(pk) = unblinded_pk {
129                                 let payload = ForwardTlvs {
130                                         next_node_id: pk,
131                                         next_blinding_override: None,
132                                 };
133                                 blinded_hops.push(BlindedHop {
134                                         blinded_node_id: prev_blinded_node_id,
135                                         encrypted_payload: encrypt_payload(payload, prev_ss),
136                                 });
137                         } else { debug_assert!(false); }
138                 }
139                 prev_ss_and_blinded_node_id = Some((encrypted_payload_ss, blinded_node_id));
140         })?;
141
142         if let Some((final_ss, final_blinded_node_id)) = prev_ss_and_blinded_node_id {
143                 let final_payload = ReceiveTlvs { path_id: None };
144                 blinded_hops.push(BlindedHop {
145                         blinded_node_id: final_blinded_node_id,
146                         encrypted_payload: encrypt_payload(final_payload, final_ss),
147                 });
148         } else { debug_assert!(false) }
149
150         Ok(blinded_hops)
151 }
152
153 /// Encrypt TLV payload to be used as a [`BlindedHop::encrypted_payload`].
154 fn encrypt_payload<P: Writeable>(payload: P, encrypted_tlvs_ss: [u8; 32]) -> Vec<u8> {
155         let mut writer = VecWriter(Vec::new());
156         let write_adapter = ChaChaPolyWriteAdapter::new(encrypted_tlvs_ss, &payload);
157         write_adapter.write(&mut writer).expect("In-memory writes cannot fail");
158         writer.0
159 }
160
161 impl Writeable for BlindedPath {
162         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
163                 self.introduction_node_id.write(w)?;
164                 self.blinding_point.write(w)?;
165                 (self.blinded_hops.len() as u8).write(w)?;
166                 for hop in &self.blinded_hops {
167                         hop.write(w)?;
168                 }
169                 Ok(())
170         }
171 }
172
173 impl Readable for BlindedPath {
174         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
175                 let introduction_node_id = Readable::read(r)?;
176                 let blinding_point = Readable::read(r)?;
177                 let num_hops: u8 = Readable::read(r)?;
178                 if num_hops == 0 { return Err(DecodeError::InvalidValue) }
179                 let mut blinded_hops: Vec<BlindedHop> = Vec::with_capacity(num_hops.into());
180                 for _ in 0..num_hops {
181                         blinded_hops.push(Readable::read(r)?);
182                 }
183                 Ok(BlindedPath {
184                         introduction_node_id,
185                         blinding_point,
186                         blinded_hops,
187                 })
188         }
189 }
190
191 impl_writeable!(BlindedHop, {
192         blinded_node_id,
193         encrypted_payload
194 });
195
196 /// TLVs to encode in an intermediate onion message packet's hop data. When provided in a blinded
197 /// route, they are encoded into [`BlindedHop::encrypted_payload`].
198 pub(crate) struct ForwardTlvs {
199         /// The node id of the next hop in the onion message's path.
200         pub(super) next_node_id: PublicKey,
201         /// Senders to a blinded path use this value to concatenate the route they find to the
202         /// introduction node with the blinded path.
203         pub(super) next_blinding_override: Option<PublicKey>,
204 }
205
206 /// Similar to [`ForwardTlvs`], but these TLVs are for the final node.
207 pub(crate) struct ReceiveTlvs {
208         /// If `path_id` is `Some`, it is used to identify the blinded path that this onion message is
209         /// sending to. This is useful for receivers to check that said blinded path is being used in
210         /// the right context.
211         pub(super) path_id: Option<[u8; 32]>,
212 }
213
214 impl Writeable for ForwardTlvs {
215         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
216                 // TODO: write padding
217                 encode_tlv_stream!(writer, {
218                         (4, self.next_node_id, required),
219                         (8, self.next_blinding_override, option)
220                 });
221                 Ok(())
222         }
223 }
224
225 impl Writeable for ReceiveTlvs {
226         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
227                 // TODO: write padding
228                 encode_tlv_stream!(writer, {
229                         (6, self.path_id, option),
230                 });
231                 Ok(())
232         }
233 }