1 // This file is Copyright its original authors, visible in version control
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
10 //! Creating blinded paths and related utilities live here.
12 use bitcoin::hashes::{Hash, HashEngine};
13 use bitcoin::hashes::sha256::Hash as Sha256;
14 use bitcoin::secp256k1::{self, PublicKey, Scalar, Secp256k1, SecretKey};
16 use crate::chain::keysinterface::{EntropySource, NodeSigner, Recipient};
17 use super::packet::ControlTlvs;
19 use crate::ln::msgs::DecodeError;
20 use crate::ln::onion_utils;
21 use crate::util::chacha20poly1305rfc::{ChaChaPolyReadAdapter, ChaChaPolyWriteAdapter};
22 use crate::util::ser::{FixedLengthReader, LengthReadableArgs, Readable, VecWriter, Writeable, Writer};
26 use crate::io::{self, Cursor};
27 use crate::prelude::*;
29 /// Onion messages can be sent and received to blinded paths, which serve to hide the identity of
31 #[derive(Clone, Debug, PartialEq)]
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's next hop and forward it along.
37 /// [`encrypted_payload`]: BlindedHop::encrypted_payload
38 pub(crate) introduction_node_id: PublicKey,
39 /// Used by the introduction node to decrypt its [`encrypted_payload`] to forward the onion
42 /// [`encrypted_payload`]: BlindedHop::encrypted_payload
43 pub(crate) blinding_point: PublicKey,
44 /// The hops composing the blinded path.
45 pub(crate) blinded_hops: Vec<BlindedHop>,
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, PartialEq)]
51 pub struct BlindedHop {
52 /// The blinded node id of this hop in a blinded path.
53 pub(crate) 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
57 pub(crate) encrypted_payload: Vec<u8>,
61 /// Create a blinded path to be forwarded along `node_pks`. The last node pubkey in `node_pks`
62 /// will be the destination node.
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<ES: EntropySource, T: secp256k1::Signing + secp256k1::Verification>
67 (node_pks: &[PublicKey], entropy_source: &ES, secp_ctx: &Secp256k1<T>) -> Result<Self, ()>
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];
76 blinding_point: PublicKey::from_secret_key(secp_ctx, &blinding_secret),
77 blinded_hops: blinded_hops(secp_ctx, node_pks, &blinding_secret).map_err(|_| ())?,
81 // Advance the blinded path by one hop, so make the second hop into the new introduction node.
82 pub(super) fn advance_by_one<NS: Deref, T: secp256k1::Signing + secp256k1::Verification>
83 (&mut self, node_signer: &NS, secp_ctx: &Secp256k1<T>) -> Result<(), ()>
84 where NS::Target: NodeSigner
86 let control_tlvs_ss = node_signer.ecdh(Recipient::Node, &self.blinding_point, None)?;
87 let rho = onion_utils::gen_rho_from_shared_secret(&control_tlvs_ss.secret_bytes());
88 let encrypted_control_tlvs = self.blinded_hops.remove(0).encrypted_payload;
89 let mut s = Cursor::new(&encrypted_control_tlvs);
90 let mut reader = FixedLengthReader::new(&mut s, encrypted_control_tlvs.len() as u64);
91 match ChaChaPolyReadAdapter::read(&mut reader, rho) {
92 Ok(ChaChaPolyReadAdapter { readable: ControlTlvs::Forward(ForwardTlvs {
93 mut next_node_id, next_blinding_override,
95 let mut new_blinding_point = match next_blinding_override {
96 Some(blinding_point) => blinding_point,
98 let blinding_factor = {
99 let mut sha = Sha256::engine();
100 sha.input(&self.blinding_point.serialize()[..]);
101 sha.input(control_tlvs_ss.as_ref());
102 Sha256::from_engine(sha).into_inner()
104 self.blinding_point.mul_tweak(secp_ctx, &Scalar::from_be_bytes(blinding_factor).unwrap())
108 mem::swap(&mut self.blinding_point, &mut new_blinding_point);
109 mem::swap(&mut self.introduction_node_id, &mut next_node_id);
117 /// Construct blinded hops for the given `unblinded_path`.
118 fn blinded_hops<T: secp256k1::Signing + secp256k1::Verification>(
119 secp_ctx: &Secp256k1<T>, unblinded_path: &[PublicKey], session_priv: &SecretKey
120 ) -> Result<Vec<BlindedHop>, secp256k1::Error> {
121 let mut blinded_hops = Vec::with_capacity(unblinded_path.len());
123 let mut prev_ss_and_blinded_node_id = None;
124 utils::construct_keys_callback(secp_ctx, unblinded_path, None, session_priv, |blinded_node_id, _, _, encrypted_payload_ss, unblinded_pk, _| {
125 if let Some((prev_ss, prev_blinded_node_id)) = prev_ss_and_blinded_node_id {
126 if let Some(pk) = unblinded_pk {
127 let payload = ForwardTlvs {
129 next_blinding_override: None,
131 blinded_hops.push(BlindedHop {
132 blinded_node_id: prev_blinded_node_id,
133 encrypted_payload: encrypt_payload(payload, prev_ss),
135 } else { debug_assert!(false); }
137 prev_ss_and_blinded_node_id = Some((encrypted_payload_ss, blinded_node_id));
140 if let Some((final_ss, final_blinded_node_id)) = prev_ss_and_blinded_node_id {
141 let final_payload = ReceiveTlvs { path_id: None };
142 blinded_hops.push(BlindedHop {
143 blinded_node_id: final_blinded_node_id,
144 encrypted_payload: encrypt_payload(final_payload, final_ss),
146 } else { debug_assert!(false) }
151 /// Encrypt TLV payload to be used as a [`BlindedHop::encrypted_payload`].
152 fn encrypt_payload<P: Writeable>(payload: P, encrypted_tlvs_ss: [u8; 32]) -> Vec<u8> {
153 let mut writer = VecWriter(Vec::new());
154 let write_adapter = ChaChaPolyWriteAdapter::new(encrypted_tlvs_ss, &payload);
155 write_adapter.write(&mut writer).expect("In-memory writes cannot fail");
159 impl Writeable for BlindedPath {
160 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
161 self.introduction_node_id.write(w)?;
162 self.blinding_point.write(w)?;
163 (self.blinded_hops.len() as u8).write(w)?;
164 for hop in &self.blinded_hops {
171 impl Readable for BlindedPath {
172 fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
173 let introduction_node_id = Readable::read(r)?;
174 let blinding_point = Readable::read(r)?;
175 let num_hops: u8 = Readable::read(r)?;
176 if num_hops == 0 { return Err(DecodeError::InvalidValue) }
177 let mut blinded_hops: Vec<BlindedHop> = Vec::with_capacity(num_hops.into());
178 for _ in 0..num_hops {
179 blinded_hops.push(Readable::read(r)?);
182 introduction_node_id,
189 impl_writeable!(BlindedHop, {
194 /// TLVs to encode in an intermediate onion message packet's hop data. When provided in a blinded
195 /// route, they are encoded into [`BlindedHop::encrypted_payload`].
196 pub(crate) struct ForwardTlvs {
197 /// The node id of the next hop in the onion message's path.
198 pub(super) next_node_id: PublicKey,
199 /// Senders to a blinded path use this value to concatenate the route they find to the
200 /// introduction node with the blinded path.
201 pub(super) next_blinding_override: Option<PublicKey>,
204 /// Similar to [`ForwardTlvs`], but these TLVs are for the final node.
205 pub(crate) struct ReceiveTlvs {
206 /// If `path_id` is `Some`, it is used to identify the blinded path that this onion message is
207 /// sending to. This is useful for receivers to check that said blinded path is being used in
208 /// the right context.
209 pub(super) path_id: Option<[u8; 32]>,
212 impl Writeable for ForwardTlvs {
213 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
214 // TODO: write padding
215 encode_tlv_stream!(writer, {
216 (4, self.next_node_id, required),
217 (8, self.next_blinding_override, option)
223 impl Writeable for ReceiveTlvs {
224 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
225 // TODO: write padding
226 encode_tlv_stream!(writer, {
227 (6, self.path_id, option),