Merge pull request #2515 from TheBlueMatt/2023-08-earlier-payment-hash-log
[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::sign::EntropySource;
19 use crate::ln::msgs::DecodeError;
20 use crate::util::ser::{Readable, Writeable, Writer};
21
22 use crate::io;
23 use crate::prelude::*;
24
25 /// Onion messages and payments can be sent and received to blinded paths, which serve to hide the
26 /// identity of the recipient.
27 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
28 pub struct BlindedPath {
29         /// To send to a blinded path, the sender first finds a route to the unblinded
30         /// `introduction_node_id`, which can unblind its [`encrypted_payload`] to find out the onion
31         /// message or payment's next hop and forward it along.
32         ///
33         /// [`encrypted_payload`]: BlindedHop::encrypted_payload
34         pub introduction_node_id: PublicKey,
35         /// Used by the introduction node to decrypt its [`encrypted_payload`] to forward the onion
36         /// message or payment.
37         ///
38         /// [`encrypted_payload`]: BlindedHop::encrypted_payload
39         pub blinding_point: PublicKey,
40         /// The hops composing the blinded path.
41         pub blinded_hops: Vec<BlindedHop>,
42 }
43
44 /// An encrypted payload and node id corresponding to a hop in a payment or onion message path, to
45 /// be encoded in the sender's onion packet. These hops cannot be identified by outside observers
46 /// and thus can be used to hide the identity of the recipient.
47 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
48 pub struct BlindedHop {
49         /// The blinded node id of this hop in a [`BlindedPath`].
50         pub blinded_node_id: PublicKey,
51         /// The encrypted payload intended for this hop in a [`BlindedPath`].
52         // The node sending to this blinded path will later encode this payload into the onion packet for
53         // this hop.
54         pub encrypted_payload: Vec<u8>,
55 }
56
57 impl BlindedPath {
58         /// Create a blinded path for an onion message, to be forwarded along `node_pks`. The last node
59         /// pubkey in `node_pks` will be the destination node.
60         ///
61         /// Errors if less than two hops are provided or if `node_pk`(s) are invalid.
62         //  TODO: make all payloads the same size with padding + add dummy hops
63         pub fn new_for_message<ES: EntropySource, T: secp256k1::Signing + secp256k1::Verification>
64                 (node_pks: &[PublicKey], entropy_source: &ES, secp_ctx: &Secp256k1<T>) -> Result<Self, ()>
65         {
66                 if node_pks.len() < 2 { return Err(()) }
67                 let blinding_secret_bytes = entropy_source.get_secure_random_bytes();
68                 let blinding_secret = SecretKey::from_slice(&blinding_secret_bytes[..]).expect("RNG is busted");
69                 let introduction_node_id = node_pks[0];
70
71                 Ok(BlindedPath {
72                         introduction_node_id,
73                         blinding_point: PublicKey::from_secret_key(secp_ctx, &blinding_secret),
74                         blinded_hops: message::blinded_hops(secp_ctx, node_pks, &blinding_secret).map_err(|_| ())?,
75                 })
76         }
77
78         /// Create a blinded path for a payment, to be forwarded along `path`. The last node
79         /// in `path` will be the destination node.
80         ///
81         /// Errors if `path` is empty or a node id in `path` is invalid.
82         //  TODO: make all payloads the same size with padding + add dummy hops
83         pub fn new_for_payment<ES: EntropySource, T: secp256k1::Signing + secp256k1::Verification>(
84                 intermediate_nodes: &[(PublicKey, payment::ForwardTlvs)], payee_node_id: PublicKey,
85                 payee_tlvs: payment::ReceiveTlvs, entropy_source: &ES, secp_ctx: &Secp256k1<T>
86         ) -> Result<Self, ()> {
87                 let blinding_secret_bytes = entropy_source.get_secure_random_bytes();
88                 let blinding_secret = SecretKey::from_slice(&blinding_secret_bytes[..]).expect("RNG is busted");
89
90                 Ok(BlindedPath {
91                         introduction_node_id: intermediate_nodes.first().map_or(payee_node_id, |n| n.0),
92                         blinding_point: PublicKey::from_secret_key(secp_ctx, &blinding_secret),
93                         blinded_hops: payment::blinded_hops(
94                                 secp_ctx, intermediate_nodes, payee_node_id, payee_tlvs, &blinding_secret
95                         ).map_err(|_| ())?,
96                 })
97         }
98 }
99
100 impl Writeable for BlindedPath {
101         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
102                 self.introduction_node_id.write(w)?;
103                 self.blinding_point.write(w)?;
104                 (self.blinded_hops.len() as u8).write(w)?;
105                 for hop in &self.blinded_hops {
106                         hop.write(w)?;
107                 }
108                 Ok(())
109         }
110 }
111
112 impl Readable for BlindedPath {
113         fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
114                 let introduction_node_id = Readable::read(r)?;
115                 let blinding_point = Readable::read(r)?;
116                 let num_hops: u8 = Readable::read(r)?;
117                 if num_hops == 0 { return Err(DecodeError::InvalidValue) }
118                 let mut blinded_hops: Vec<BlindedHop> = Vec::with_capacity(num_hops.into());
119                 for _ in 0..num_hops {
120                         blinded_hops.push(Readable::read(r)?);
121                 }
122                 Ok(BlindedPath {
123                         introduction_node_id,
124                         blinding_point,
125                         blinded_hops,
126                 })
127         }
128 }
129
130 impl_writeable!(BlindedHop, {
131         blinded_node_id,
132         encrypted_payload
133 });
134