Move some blinded path message code into message submodule.
[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 message;
13 pub(crate) mod utils;
14
15 use bitcoin::secp256k1::{self, PublicKey, Secp256k1, SecretKey};
16
17 use crate::sign::{EntropySource, NodeSigner, Recipient};
18 use crate::onion_message::ControlTlvs;
19 use crate::ln::msgs::DecodeError;
20 use crate::ln::onion_utils;
21 use crate::util::chacha20poly1305rfc::ChaChaPolyReadAdapter;
22 use crate::util::ser::{FixedLengthReader, LengthReadableArgs, Readable, Writeable, Writer};
23
24 use core::mem;
25 use core::ops::Deref;
26 use crate::io::{self, Cursor};
27 use crate::prelude::*;
28
29 /// Onion messages and payments can be sent and received to blinded paths, which serve to hide the
30 /// identity of the recipient.
31 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
32 pub struct BlindedPath {
33         /// To send to a blinded path, the sender first finds a route to the unblinded
34         /// `introduction_node_id`, which can unblind its [`encrypted_payload`] to find out the onion
35         /// message or payment's next hop and forward it along.
36         ///
37         /// [`encrypted_payload`]: BlindedHop::encrypted_payload
38         pub introduction_node_id: PublicKey,
39         /// Used by the introduction node to decrypt its [`encrypted_payload`] to forward the onion
40         /// message or payment.
41         ///
42         /// [`encrypted_payload`]: BlindedHop::encrypted_payload
43         pub blinding_point: PublicKey,
44         /// The hops composing the blinded path.
45         pub blinded_hops: Vec<BlindedHop>,
46 }
47
48 /// Used to construct the blinded hops portion of a blinded path. These hops cannot be identified
49 /// by outside observers and thus can be used to hide the identity of the recipient.
50 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
51 pub struct BlindedHop {
52         /// The blinded node id of this hop in a blinded path.
53         pub blinded_node_id: PublicKey,
54         /// The encrypted payload intended for this hop in a blinded path.
55         // The node sending to this blinded path will later encode this payload into the onion packet for
56         // this hop.
57         pub encrypted_payload: Vec<u8>,
58 }
59
60 impl BlindedPath {
61         /// Create a blinded path for an onion message, to be forwarded along `node_pks`. The last node
62         /// pubkey in `node_pks` will be the destination node.
63         ///
64         /// Errors if less than two hops are provided or if `node_pk`(s) are invalid.
65         //  TODO: make all payloads the same size with padding + add dummy hops
66         pub fn new_for_message<ES: EntropySource, T: secp256k1::Signing + secp256k1::Verification>
67                 (node_pks: &[PublicKey], entropy_source: &ES, secp_ctx: &Secp256k1<T>) -> Result<Self, ()>
68         {
69                 if node_pks.len() < 2 { return Err(()) }
70                 let blinding_secret_bytes = entropy_source.get_secure_random_bytes();
71                 let blinding_secret = SecretKey::from_slice(&blinding_secret_bytes[..]).expect("RNG is busted");
72                 let introduction_node_id = node_pks[0];
73
74                 Ok(BlindedPath {
75                         introduction_node_id,
76                         blinding_point: PublicKey::from_secret_key(secp_ctx, &blinding_secret),
77                         blinded_hops: message::blinded_hops(secp_ctx, node_pks, &blinding_secret).map_err(|_| ())?,
78                 })
79         }
80
81         // Advance the blinded onion message path by one hop, so make the second hop into the new
82         // introduction node.
83         pub(super) fn advance_message_path_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(message::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                                                 onion_utils::next_hop_pubkey(secp_ctx, self.blinding_point,
100                                                         control_tlvs_ss.as_ref()).map_err(|_| ())?
101                                         }
102                                 };
103                                 mem::swap(&mut self.blinding_point, &mut new_blinding_point);
104                                 mem::swap(&mut self.introduction_node_id, &mut next_node_id);
105                                 Ok(())
106                         },
107                         _ => Err(())
108                 }
109         }
110 }
111
112 impl Writeable for BlindedPath {
113         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
114                 self.introduction_node_id.write(w)?;
115                 self.blinding_point.write(w)?;
116                 (self.blinded_hops.len() as u8).write(w)?;
117                 for hop in &self.blinded_hops {
118                         hop.write(w)?;
119                 }
120                 Ok(())
121         }
122 }
123
124 impl Readable for BlindedPath {
125         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
126                 let introduction_node_id = Readable::read(r)?;
127                 let blinding_point = Readable::read(r)?;
128                 let num_hops: u8 = Readable::read(r)?;
129                 if num_hops == 0 { return Err(DecodeError::InvalidValue) }
130                 let mut blinded_hops: Vec<BlindedHop> = Vec::with_capacity(num_hops.into());
131                 for _ in 0..num_hops {
132                         blinded_hops.push(Readable::read(r)?);
133                 }
134                 Ok(BlindedPath {
135                         introduction_node_id,
136                         blinding_point,
137                         blinded_hops,
138                 })
139         }
140 }
141
142 impl_writeable!(BlindedHop, {
143         blinded_node_id,
144         encrypted_payload
145 });
146