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