9f1d8db46dd84d3477600e1d5a19015b3cb9e6aa
[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::secp256k1::{self, PublicKey, Secp256k1, SecretKey};
13
14 use chain::keysinterface::{KeysInterface, Sign};
15 use super::utils;
16 use ln::msgs::DecodeError;
17 use util::chacha20poly1305rfc::ChaChaPolyWriteAdapter;
18 use util::ser::{Readable, VecWriter, Writeable, Writer};
19
20 use io;
21 use prelude::*;
22
23 /// Onion messages can be sent and received to blinded routes, which serve to hide the identity of
24 /// the recipient.
25 pub struct BlindedRoute {
26         /// To send to a blinded route, the sender first finds a route to the unblinded
27         /// `introduction_node_id`, which can unblind its [`encrypted_payload`] to find out the onion
28         /// message's next hop and forward it along.
29         ///
30         /// [`encrypted_payload`]: BlindedHop::encrypted_payload
31         pub(super) introduction_node_id: PublicKey,
32         /// Used by the introduction node to decrypt its [`encrypted_payload`] to forward the onion
33         /// message.
34         ///
35         /// [`encrypted_payload`]: BlindedHop::encrypted_payload
36         pub(super) blinding_point: PublicKey,
37         /// The hops composing the blinded route.
38         pub(super) blinded_hops: Vec<BlindedHop>,
39 }
40
41 /// Used to construct the blinded hops portion of a blinded route. These hops cannot be identified
42 /// by outside observers and thus can be used to hide the identity of the recipient.
43 pub struct BlindedHop {
44         /// The blinded node id of this hop in a blinded route.
45         pub(super) blinded_node_id: PublicKey,
46         /// The encrypted payload intended for this hop in a blinded route.
47         // The node sending to this blinded route will later encode this payload into the onion packet for
48         // this hop.
49         pub(super) encrypted_payload: Vec<u8>,
50 }
51
52 impl BlindedRoute {
53         /// Create a blinded route to be forwarded along `node_pks`. The last node pubkey in `node_pks`
54         /// will be the destination node.
55         ///
56         /// Errors if less than two hops are provided or if `node_pk`(s) are invalid.
57         //  TODO: make all payloads the same size with padding + add dummy hops
58         pub fn new<Signer: Sign, K: KeysInterface, T: secp256k1::Signing + secp256k1::Verification>
59                 (node_pks: &[PublicKey], keys_manager: &K, secp_ctx: &Secp256k1<T>) -> Result<Self, ()>
60         {
61                 if node_pks.len() < 2 { return Err(()) }
62                 let blinding_secret_bytes = keys_manager.get_secure_random_bytes();
63                 let blinding_secret = SecretKey::from_slice(&blinding_secret_bytes[..]).expect("RNG is busted");
64                 let introduction_node_id = node_pks[0];
65
66                 Ok(BlindedRoute {
67                         introduction_node_id,
68                         blinding_point: PublicKey::from_secret_key(secp_ctx, &blinding_secret),
69                         blinded_hops: blinded_hops(secp_ctx, node_pks, &blinding_secret).map_err(|_| ())?,
70                 })
71         }
72 }
73
74 /// Construct blinded hops for the given `unblinded_path`.
75 fn blinded_hops<T: secp256k1::Signing + secp256k1::Verification>(
76         secp_ctx: &Secp256k1<T>, unblinded_path: &[PublicKey], session_priv: &SecretKey
77 ) -> Result<Vec<BlindedHop>, secp256k1::Error> {
78         let mut blinded_hops = Vec::with_capacity(unblinded_path.len());
79
80         let mut prev_ss_and_blinded_node_id = None;
81         utils::construct_keys_callback(secp_ctx, unblinded_path, None, session_priv, |blinded_node_id, _, _, encrypted_payload_ss, unblinded_pk, _| {
82                 if let Some((prev_ss, prev_blinded_node_id)) = prev_ss_and_blinded_node_id {
83                         if let Some(pk) = unblinded_pk {
84                                 let payload = ForwardTlvs {
85                                         next_node_id: pk,
86                                         next_blinding_override: None,
87                                 };
88                                 blinded_hops.push(BlindedHop {
89                                         blinded_node_id: prev_blinded_node_id,
90                                         encrypted_payload: encrypt_payload(payload, prev_ss),
91                                 });
92                         } else { debug_assert!(false); }
93                 }
94                 prev_ss_and_blinded_node_id = Some((encrypted_payload_ss, blinded_node_id));
95         })?;
96
97         if let Some((final_ss, final_blinded_node_id)) = prev_ss_and_blinded_node_id {
98                 let final_payload = ReceiveTlvs { path_id: None };
99                 blinded_hops.push(BlindedHop {
100                         blinded_node_id: final_blinded_node_id,
101                         encrypted_payload: encrypt_payload(final_payload, final_ss),
102                 });
103         } else { debug_assert!(false) }
104
105         Ok(blinded_hops)
106 }
107
108 /// Encrypt TLV payload to be used as a [`BlindedHop::encrypted_payload`].
109 fn encrypt_payload<P: Writeable>(payload: P, encrypted_tlvs_ss: [u8; 32]) -> Vec<u8> {
110         let mut writer = VecWriter(Vec::new());
111         let write_adapter = ChaChaPolyWriteAdapter::new(encrypted_tlvs_ss, &payload);
112         write_adapter.write(&mut writer).expect("In-memory writes cannot fail");
113         writer.0
114 }
115
116 impl Writeable for BlindedRoute {
117         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
118                 self.introduction_node_id.write(w)?;
119                 self.blinding_point.write(w)?;
120                 (self.blinded_hops.len() as u8).write(w)?;
121                 for hop in &self.blinded_hops {
122                         hop.write(w)?;
123                 }
124                 Ok(())
125         }
126 }
127
128 impl Readable for BlindedRoute {
129         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
130                 let introduction_node_id = Readable::read(r)?;
131                 let blinding_point = Readable::read(r)?;
132                 let num_hops: u8 = Readable::read(r)?;
133                 if num_hops == 0 { return Err(DecodeError::InvalidValue) }
134                 let mut blinded_hops: Vec<BlindedHop> = Vec::with_capacity(num_hops.into());
135                 for _ in 0..num_hops {
136                         blinded_hops.push(Readable::read(r)?);
137                 }
138                 Ok(BlindedRoute {
139                         introduction_node_id,
140                         blinding_point,
141                         blinded_hops,
142                 })
143         }
144 }
145
146 impl_writeable!(BlindedHop, {
147         blinded_node_id,
148         encrypted_payload
149 });
150
151 /// TLVs to encode in an intermediate onion message packet's hop data. When provided in a blinded
152 /// route, they are encoded into [`BlindedHop::encrypted_payload`].
153 pub(crate) struct ForwardTlvs {
154         /// The node id of the next hop in the onion message's path.
155         pub(super) next_node_id: PublicKey,
156         /// Senders to a blinded route use this value to concatenate the route they find to the
157         /// introduction node with the blinded route.
158         pub(super) next_blinding_override: Option<PublicKey>,
159 }
160
161 /// Similar to [`ForwardTlvs`], but these TLVs are for the final node.
162 pub(crate) struct ReceiveTlvs {
163         /// If `path_id` is `Some`, it is used to identify the blinded route that this onion message is
164         /// sending to. This is useful for receivers to check that said blinded route is being used in
165         /// the right context.
166         pub(super) path_id: Option<[u8; 32]>,
167 }
168
169 impl Writeable for ForwardTlvs {
170         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
171                 // TODO: write padding
172                 encode_tlv_stream!(writer, {
173                         (4, self.next_node_id, required),
174                         (8, self.next_blinding_override, option)
175                 });
176                 Ok(())
177         }
178 }
179
180 impl Writeable for ReceiveTlvs {
181         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
182                 // TODO: write padding
183                 encode_tlv_stream!(writer, {
184                         (6, self.path_id, option),
185                 });
186                 Ok(())
187         }
188 }