d18372e3b009bb09d82a5d7b6eb62ebcdda7d4ca
[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 util::chacha20poly1305rfc::ChaChaPolyWriteAdapter;
17 use util::ser::{VecWriter, Writeable, Writer};
18
19 use core::iter::FromIterator;
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 /// TLVs to encode in an intermediate onion message packet's hop data. When provided in a blinded
117 /// route, they are encoded into [`BlindedHop::encrypted_payload`].
118 pub(crate) struct ForwardTlvs {
119         /// The node id of the next hop in the onion message's path.
120         pub(super) next_node_id: PublicKey,
121         /// Senders to a blinded route use this value to concatenate the route they find to the
122         /// introduction node with the blinded route.
123         pub(super) next_blinding_override: Option<PublicKey>,
124 }
125
126 /// Similar to [`ForwardTlvs`], but these TLVs are for the final node.
127 pub(crate) struct ReceiveTlvs {
128         /// If `path_id` is `Some`, it is used to identify the blinded route that this onion message is
129         /// sending to. This is useful for receivers to check that said blinded route is being used in
130         /// the right context.
131         pub(super) path_id: Option<[u8; 32]>,
132 }
133
134 impl Writeable for ForwardTlvs {
135         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
136                 // TODO: write padding
137                 encode_tlv_stream!(writer, {
138                         (4, self.next_node_id, required),
139                         (8, self.next_blinding_override, option)
140                 });
141                 Ok(())
142         }
143 }
144
145 impl Writeable for ReceiveTlvs {
146         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
147                 // TODO: write padding
148                 encode_tlv_stream!(writer, {
149                         (6, self.path_id, option),
150                 });
151                 Ok(())
152         }
153 }