Add BlindedPath::introduction_node_id method
[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 mod payment;
13 pub(crate) mod message;
14 pub(crate) mod utils;
15
16 use bitcoin::secp256k1::{self, PublicKey, Secp256k1, SecretKey};
17
18 use crate::ln::msgs::DecodeError;
19 use crate::offers::invoice::BlindedPayInfo;
20 use crate::routing::gossip::{NodeId, ReadOnlyNetworkGraph};
21 use crate::sign::EntropySource;
22 use crate::util::ser::{Readable, Writeable, Writer};
23
24 use crate::io;
25 use crate::prelude::*;
26
27 /// Onion messages and payments can be sent and received to blinded paths, which serve to hide the
28 /// identity of the recipient.
29 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
30 pub struct BlindedPath {
31         /// To send to a blinded path, the sender first finds a route to the unblinded
32         /// `introduction_node_id`, which can unblind its [`encrypted_payload`] to find out the onion
33         /// message or payment's next hop and forward it along.
34         ///
35         /// [`encrypted_payload`]: BlindedHop::encrypted_payload
36         pub introduction_node_id: PublicKey,
37         /// Used by the introduction node to decrypt its [`encrypted_payload`] to forward the onion
38         /// message or payment.
39         ///
40         /// [`encrypted_payload`]: BlindedHop::encrypted_payload
41         pub blinding_point: PublicKey,
42         /// The hops composing the blinded path.
43         pub blinded_hops: Vec<BlindedHop>,
44 }
45
46 /// An encrypted payload and node id corresponding to a hop in a payment or onion message path, to
47 /// be encoded in the sender's onion packet. These hops cannot be identified by outside observers
48 /// 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 [`BlindedPath`].
52         pub blinded_node_id: PublicKey,
53         /// The encrypted payload intended for this hop in a [`BlindedPath`].
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 one-hop blinded path for a message.
61         pub fn one_hop_for_message<ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification>(
62                 recipient_node_id: PublicKey, entropy_source: &ES, secp_ctx: &Secp256k1<T>
63         ) -> Result<Self, ()> {
64                 Self::new_for_message(&[recipient_node_id], entropy_source, secp_ctx)
65         }
66
67         /// Create a blinded path for an onion message, to be forwarded along `node_pks`. The last node
68         /// pubkey in `node_pks` will be the destination node.
69         ///
70         /// Errors if no hops are provided or if `node_pk`(s) are invalid.
71         //  TODO: make all payloads the same size with padding + add dummy hops
72         pub fn new_for_message<ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification>(
73                 node_pks: &[PublicKey], entropy_source: &ES, secp_ctx: &Secp256k1<T>
74         ) -> Result<Self, ()> {
75                 if node_pks.is_empty() { return Err(()) }
76                 let blinding_secret_bytes = entropy_source.get_secure_random_bytes();
77                 let blinding_secret = SecretKey::from_slice(&blinding_secret_bytes[..]).expect("RNG is busted");
78                 let introduction_node_id = node_pks[0];
79
80                 Ok(BlindedPath {
81                         introduction_node_id,
82                         blinding_point: PublicKey::from_secret_key(secp_ctx, &blinding_secret),
83                         blinded_hops: message::blinded_hops(secp_ctx, node_pks, &blinding_secret).map_err(|_| ())?,
84                 })
85         }
86
87         /// Create a one-hop blinded path for a payment.
88         pub fn one_hop_for_payment<ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification>(
89                 payee_node_id: PublicKey, payee_tlvs: payment::ReceiveTlvs, min_final_cltv_expiry_delta: u16,
90                 entropy_source: &ES, secp_ctx: &Secp256k1<T>
91         ) -> Result<(BlindedPayInfo, Self), ()> {
92                 // This value is not considered in pathfinding for 1-hop blinded paths, because it's intended to
93                 // be in relation to a specific channel.
94                 let htlc_maximum_msat = u64::max_value();
95                 Self::new_for_payment(
96                         &[], payee_node_id, payee_tlvs, htlc_maximum_msat, min_final_cltv_expiry_delta,
97                         entropy_source, secp_ctx
98                 )
99         }
100
101         /// Create a blinded path for a payment, to be forwarded along `intermediate_nodes`.
102         ///
103         /// Errors if:
104         /// * a provided node id is invalid
105         /// * [`BlindedPayInfo`] calculation results in an integer overflow
106         /// * any unknown features are required in the provided [`ForwardTlvs`]
107         ///
108         /// [`ForwardTlvs`]: crate::blinded_path::payment::ForwardTlvs
109         //  TODO: make all payloads the same size with padding + add dummy hops
110         pub fn new_for_payment<ES: EntropySource + ?Sized, T: secp256k1::Signing + secp256k1::Verification>(
111                 intermediate_nodes: &[payment::ForwardNode], payee_node_id: PublicKey,
112                 payee_tlvs: payment::ReceiveTlvs, htlc_maximum_msat: u64, min_final_cltv_expiry_delta: u16,
113                 entropy_source: &ES, secp_ctx: &Secp256k1<T>
114         ) -> Result<(BlindedPayInfo, Self), ()> {
115                 let blinding_secret_bytes = entropy_source.get_secure_random_bytes();
116                 let blinding_secret = SecretKey::from_slice(&blinding_secret_bytes[..]).expect("RNG is busted");
117
118                 let blinded_payinfo = payment::compute_payinfo(
119                         intermediate_nodes, &payee_tlvs, htlc_maximum_msat, min_final_cltv_expiry_delta
120                 )?;
121                 Ok((blinded_payinfo, BlindedPath {
122                         introduction_node_id: intermediate_nodes.first().map_or(payee_node_id, |n| n.node_id),
123                         blinding_point: PublicKey::from_secret_key(secp_ctx, &blinding_secret),
124                         blinded_hops: payment::blinded_hops(
125                                 secp_ctx, intermediate_nodes, payee_node_id, payee_tlvs, &blinding_secret
126                         ).map_err(|_| ())?,
127                 }))
128         }
129
130         /// Returns the introduction [`NodeId`] of the blinded path.
131         pub fn public_introduction_node_id<'a>(
132                 &self, network_graph: &'a ReadOnlyNetworkGraph
133         ) -> Option<&'a NodeId> {
134                 let node_id = NodeId::from_pubkey(&self.introduction_node_id);
135                 network_graph.nodes().get_key_value(&node_id).map(|(key, _)| key)
136         }
137 }
138
139 impl Writeable for BlindedPath {
140         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
141                 self.introduction_node_id.write(w)?;
142                 self.blinding_point.write(w)?;
143                 (self.blinded_hops.len() as u8).write(w)?;
144                 for hop in &self.blinded_hops {
145                         hop.write(w)?;
146                 }
147                 Ok(())
148         }
149 }
150
151 impl Readable for BlindedPath {
152         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
153                 let introduction_node_id = Readable::read(r)?;
154                 let blinding_point = Readable::read(r)?;
155                 let num_hops: u8 = Readable::read(r)?;
156                 if num_hops == 0 { return Err(DecodeError::InvalidValue) }
157                 let mut blinded_hops: Vec<BlindedHop> = Vec::with_capacity(num_hops.into());
158                 for _ in 0..num_hops {
159                         blinded_hops.push(Readable::read(r)?);
160                 }
161                 Ok(BlindedPath {
162                         introduction_node_id,
163                         blinding_point,
164                         blinded_hops,
165                 })
166         }
167 }
168
169 impl_writeable!(BlindedHop, {
170         blinded_node_id,
171         encrypted_payload
172 });
173