Skip to content

Commit 050268a

Browse files
Implement receiving and forwarding onion messages
This required adapting `onion_utils::decode_next_hop` to work for both payments and onion messages. Currently we just print out the path_id of any onion messages we receive. In the future, these received onion messages will be redirected to their respective handlers: i.e. an invoice_request will go to an InvoiceHandler, custom onion messages will go to a custom handler, etc.
1 parent 8af37eb commit 050268a

File tree

3 files changed

+215
-20
lines changed

3 files changed

+215
-20
lines changed

lightning/src/ln/channelmanager.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -2136,7 +2136,7 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
21362136
}
21372137
}
21382138

2139-
let next_hop = match onion_utils::decode_next_hop(shared_secret, &msg.onion_routing_packet.hop_data[..], msg.onion_routing_packet.hmac, msg.payment_hash) {
2139+
let next_hop = match onion_utils::decode_next_payment_hop(shared_secret, &msg.onion_routing_packet.hop_data[..], msg.onion_routing_packet.hmac, msg.payment_hash) {
21402140
Ok(res) => res,
21412141
Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
21422142
return_malformed_err!(err_msg, err_code);
@@ -2952,7 +2952,7 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
29522952
let phantom_secret_res = self.keys_manager.get_node_secret(Recipient::PhantomNode);
29532953
if phantom_secret_res.is_ok() && fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, short_chan_id) {
29542954
let phantom_shared_secret = SharedSecret::new(&onion_packet.public_key.unwrap(), &phantom_secret_res.unwrap()).secret_bytes();
2955-
let next_hop = match onion_utils::decode_next_hop(phantom_shared_secret, &onion_packet.hop_data, onion_packet.hmac, payment_hash) {
2955+
let next_hop = match onion_utils::decode_next_payment_hop(phantom_shared_secret, &onion_packet.hop_data, onion_packet.hmac, payment_hash) {
29562956
Ok(res) => res,
29572957
Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
29582958
let sha256_of_onion = Sha256::hash(&onion_packet.hop_data).into_inner();

lightning/src/ln/onion_message.rs

+116-4
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,13 @@ use bitcoin::hashes::sha256::Hash as Sha256;
1414
use bitcoin::secp256k1::{self, PublicKey, Secp256k1, SecretKey};
1515
use bitcoin::secp256k1::ecdh::SharedSecret;
1616

17-
use chain::keysinterface::{InMemorySigner, KeysInterface, KeysManager, Sign};
17+
use chain::keysinterface::{InMemorySigner, KeysInterface, KeysManager, Recipient, Sign};
1818
use ln::msgs::{self, DecodeError, OnionMessageHandler};
1919
use ln::onion_utils;
20-
use util::chacha20poly1305rfc::{ChaCha20Poly1305RFC, ChaChaPoly1305Writer};
20+
use util::chacha20poly1305rfc::{ChaChaPoly1305Reader, ChaCha20Poly1305RFC, ChaChaPoly1305Writer};
2121
use util::events::{MessageSendEvent, MessageSendEventsProvider};
2222
use util::logger::Logger;
23-
use util::ser::{LengthCalculatingWriter, Readable, ReadableArgs, VecWriter, Writeable, Writer};
23+
use util::ser::{FixedLengthReader, LengthCalculatingWriter, Readable, ReadableArgs, VecWriter, Writeable, Writer};
2424

2525
use core::mem;
2626
use core::ops::Deref;
@@ -121,6 +121,40 @@ impl Writeable for (Payload, SharedSecret) {
121121
}
122122
}
123123

124+
/// Reads of `Payload`s are parameterized by the `rho` of a `SharedSecret`, which is used to decrypt
125+
/// the onion message payload's `encrypted_data` field.
126+
impl ReadableArgs<SharedSecret> for Payload {
127+
fn read<R: Read>(mut r: &mut R, encrypted_tlvs_ss: SharedSecret) -> Result<Self, DecodeError> {
128+
use bitcoin::consensus::encode::{Decodable, Error, VarInt};
129+
let v: VarInt = Decodable::consensus_decode(&mut r)
130+
.map_err(|e| match e {
131+
Error::Io(ioe) => DecodeError::from(ioe),
132+
_ => DecodeError::InvalidValue
133+
})?;
134+
if v.0 == 0 { // 0-length payload
135+
return Err(DecodeError::InvalidValue)
136+
}
137+
138+
let mut rd = FixedLengthReader::new(r, v.0);
139+
// TODO: support reply paths
140+
let mut _reply_path_bytes: Option<Vec<u8>> = Some(Vec::new());
141+
let mut control_tlvs: Option<ControlTlvs> = None;
142+
decode_tlv_stream!(&mut rd, {
143+
(2, _reply_path_bytes, vec_type),
144+
(4, control_tlvs, (chacha, encrypted_tlvs_ss))
145+
});
146+
rd.eat_remaining().map_err(|_| DecodeError::ShortRead)?;
147+
148+
if control_tlvs.is_none() {
149+
return Err(DecodeError::InvalidValue)
150+
}
151+
152+
Ok(Payload {
153+
encrypted_tlvs: EncryptedTlvs::Unblinded(control_tlvs.unwrap()),
154+
})
155+
}
156+
}
157+
124158
/// Onion messages contain an encrypted TLV stream. This can be supplied by someone else, in the
125159
/// case that we're sending to a blinded route, or created by us if we're constructing payloads for
126160
/// unblinded hops in the onion message's path.
@@ -393,7 +427,85 @@ impl<Signer: Sign, K: Deref, L: Deref> OnionMessageHandler for OnionMessenger<Si
393427
where K::Target: KeysInterface<Signer = Signer>,
394428
L::Target: Logger,
395429
{
396-
fn handle_onion_message(&self, _peer_node_id: &PublicKey, msg: &msgs::OnionMessage) {}
430+
fn handle_onion_message(&self, _peer_node_id: &PublicKey, msg: &msgs::OnionMessage) {
431+
let node_secret = match self.keys_manager.get_node_secret(Recipient::Node) {
432+
Ok(secret) => secret,
433+
Err(e) => {
434+
log_trace!(self.logger, "Failed to retrieve node secret: {:?}", e);
435+
return
436+
}
437+
};
438+
let encrypted_data_ss = SharedSecret::new(&msg.blinding_point, &node_secret);
439+
let onion_decode_shared_secret = {
440+
let blinding_factor = {
441+
let mut hmac = HmacEngine::<Sha256>::new(b"blinded_node_id");
442+
hmac.input(encrypted_data_ss.as_ref());
443+
Hmac::from_engine(hmac).into_inner()
444+
};
445+
let mut blinded_priv = node_secret.clone();
446+
if let Err(e) = blinded_priv.mul_assign(&blinding_factor) {
447+
log_trace!(self.logger, "Failed to compute blinded public key: {}", e);
448+
return
449+
}
450+
if let Err(_) = msg.onion_routing_packet.public_key {
451+
log_trace!(self.logger, "Failed to accept/forward incoming onion message: invalid ephemeral pubkey");
452+
return
453+
}
454+
SharedSecret::new(&msg.onion_routing_packet.public_key.unwrap(), &blinded_priv).secret_bytes()
455+
};
456+
match onion_utils::decode_next_message_hop(onion_decode_shared_secret, &msg.onion_routing_packet.hop_data[..], msg.onion_routing_packet.hmac, encrypted_data_ss) {
457+
Ok(onion_utils::MessageHop::Receive(Payload {
458+
encrypted_tlvs: EncryptedTlvs::Unblinded(ControlTlvs::Receive { path_id })
459+
})) => {
460+
log_info!(self.logger, "Received an onion message with path_id: {:02x?}", path_id);
461+
},
462+
Ok(onion_utils::MessageHop::Forward {
463+
next_hop_data: Payload {
464+
encrypted_tlvs: EncryptedTlvs::Unblinded(ControlTlvs::Forward { next_node_id, next_blinding_override }),
465+
},
466+
next_hop_hmac, new_packet_bytes
467+
}) => {
468+
let new_pubkey = msg.onion_routing_packet.public_key.unwrap();
469+
let outgoing_packet = Packet {
470+
version: 0,
471+
public_key: onion_utils::next_hop_packet_pubkey(&self.secp_ctx, new_pubkey, &onion_decode_shared_secret),
472+
hop_data: new_packet_bytes.to_vec(),
473+
hmac: next_hop_hmac.clone(),
474+
};
475+
476+
let mut pending_msg_events = self.pending_msg_events.lock().unwrap();
477+
pending_msg_events.push(MessageSendEvent::SendOnionMessage {
478+
node_id: next_node_id,
479+
msg: msgs::OnionMessage {
480+
blinding_point: match next_blinding_override {
481+
Some(blinding_point) => blinding_point,
482+
None => {
483+
let blinding_factor = {
484+
let mut sha = Sha256::engine();
485+
sha.input(&msg.blinding_point.serialize()[..]);
486+
sha.input(encrypted_data_ss.as_ref());
487+
Sha256::from_engine(sha).into_inner()
488+
};
489+
let mut next_blinding_point = msg.blinding_point.clone();
490+
if let Err(e) = next_blinding_point.mul_assign(&self.secp_ctx, &blinding_factor[..]) {
491+
log_trace!(self.logger, "Failed to compute next blinding point: {}", e);
492+
return
493+
}
494+
next_blinding_point
495+
},
496+
},
497+
len: new_packet_bytes.len() as u16 + 66,
498+
onion_routing_packet: outgoing_packet,
499+
},
500+
});
501+
},
502+
Err(e) => {
503+
log_trace!(self.logger, "Errored decoding onion message packet: {:?}", e);
504+
},
505+
_ => {}, // This is unreachable unless someone encoded an onion message very weirdly, in which
506+
// case it should be fine to just drop it
507+
};
508+
}
397509
}
398510

399511
impl<Signer: Sign, K: Deref, L: Deref> MessageSendEventsProvider for OnionMessenger<Signer, K, L>

lightning/src/ln/onion_utils.rs

+97-14
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use routing::network_graph::NetworkUpdate;
1616
use routing::router::RouteHop;
1717
use util::chacha20::{ChaCha20, ChaChaReader};
1818
use util::errors::{self, APIError};
19-
use util::ser::{Readable, Writeable, LengthCalculatingWriter};
19+
use util::ser::{Readable, ReadableArgs, Writeable, LengthCalculatingWriter};
2020
use util::logger::Logger;
2121

2222
use bitcoin::hashes::{Hash, HashEngine};
@@ -636,7 +636,37 @@ pub(super) fn process_onion_failure<T: secp256k1::Signing, L: Deref>(secp_ctx: &
636636
} else { unreachable!(); }
637637
}
638638

639-
/// Data decrypted from the onion payload.
639+
/// Used in the decoding of inbound payments' and onion messages' routing packets. This enum allows
640+
/// us to use `decode_next_hop` to return the payloads and next hop packet bytes of both payments
641+
/// and onion messages.
642+
enum Payload {
643+
/// This payload was for an incoming payment.
644+
Payment(msgs::OnionHopData),
645+
/// This payload was for an incoming onion message.
646+
Message(onion_message::Payload),
647+
}
648+
649+
enum NextPacketBytes {
650+
Payment([u8; 20*65]),
651+
Message(Vec<u8>),
652+
}
653+
654+
/// Data decrypted from an onion message's onion payload.
655+
pub(crate) enum MessageHop {
656+
/// This onion payload was for us, not for forwarding to a next-hop.
657+
Receive(onion_message::Payload),
658+
/// This onion payload needs to be forwarded to a next-hop.
659+
Forward {
660+
/// Onion payload data used in forwarding the onion message.
661+
next_hop_data: onion_message::Payload,
662+
/// HMAC of the next hop's onion packet.
663+
next_hop_hmac: [u8; 32],
664+
/// Bytes of the onion packet we're forwarding.
665+
new_packet_bytes: Vec<u8>,
666+
},
667+
}
668+
669+
/// Data decrypted from a payment's onion payload.
640670
pub(crate) enum Hop {
641671
/// This onion payload was for us, not for forwarding to a next-hop. Contains information for
642672
/// verifying the incoming payment.
@@ -653,6 +683,7 @@ pub(crate) enum Hop {
653683
}
654684

655685
/// Error returned when we fail to decode the onion packet.
686+
#[derive(Debug)]
656687
pub(crate) enum OnionDecodeErr {
657688
/// The HMAC of the onion packet did not match the hop data.
658689
Malformed {
@@ -666,11 +697,44 @@ pub(crate) enum OnionDecodeErr {
666697
},
667698
}
668699

669-
pub(crate) fn decode_next_hop(shared_secret: [u8; 32], hop_data: &[u8], hmac_bytes: [u8; 32], payment_hash: PaymentHash) -> Result<Hop, OnionDecodeErr> {
700+
pub(crate) fn decode_next_message_hop(shared_secret: [u8; 32], hop_data: &[u8], hmac_bytes: [u8; 32], encrypted_tlvs_ss: SharedSecret) -> Result<MessageHop, OnionDecodeErr> {
701+
match decode_next_hop(shared_secret, hop_data, hmac_bytes, None, Some(encrypted_tlvs_ss)) {
702+
Ok((Payload::Message(next_hop_data), None)) => Ok(MessageHop::Receive(next_hop_data)),
703+
Ok((Payload::Message(next_hop_data), Some((next_hop_hmac, NextPacketBytes::Message(new_packet_bytes))))) => {
704+
Ok(MessageHop::Forward {
705+
next_hop_data,
706+
next_hop_hmac,
707+
new_packet_bytes
708+
})
709+
},
710+
Err(e) => Err(e),
711+
_ => unreachable!()
712+
}
713+
}
714+
715+
pub(crate) fn decode_next_payment_hop(shared_secret: [u8; 32], hop_data: &[u8], hmac_bytes: [u8; 32], payment_hash: PaymentHash) -> Result<Hop, OnionDecodeErr> {
716+
match decode_next_hop(shared_secret, hop_data, hmac_bytes, Some(payment_hash), None) {
717+
Ok((Payload::Payment(next_hop_data), None)) => Ok(Hop::Receive(next_hop_data)),
718+
Ok((Payload::Payment(next_hop_data), Some((next_hop_hmac, NextPacketBytes::Payment(new_packet_bytes))))) => {
719+
Ok(Hop::Forward {
720+
next_hop_data,
721+
next_hop_hmac,
722+
new_packet_bytes
723+
})
724+
},
725+
Err(e) => Err(e),
726+
_ => unreachable!()
727+
}
728+
}
729+
730+
fn decode_next_hop(shared_secret: [u8; 32], hop_data: &[u8], hmac_bytes: [u8; 32], payment_hash: Option<PaymentHash>, encrypted_tlv_ss: Option<SharedSecret>) -> Result<(Payload, Option<([u8; 32], NextPacketBytes)>), OnionDecodeErr> {
731+
assert!(payment_hash.is_some() && encrypted_tlv_ss.is_none() || payment_hash.is_none() && encrypted_tlv_ss.is_some());
670732
let (rho, mu) = gen_rho_mu_from_shared_secret(&shared_secret);
671733
let mut hmac = HmacEngine::<Sha256>::new(&mu);
672734
hmac.input(hop_data);
673-
hmac.input(&payment_hash.0[..]);
735+
if let Some(payment_hash) = payment_hash {
736+
hmac.input(&payment_hash.0[..]);
737+
}
674738
if !fixed_time_eq(&Hmac::from_engine(hmac).into_inner(), &hmac_bytes) {
675739
return Err(OnionDecodeErr::Malformed {
676740
err_msg: "HMAC Check failed",
@@ -680,7 +744,20 @@ pub(crate) fn decode_next_hop(shared_secret: [u8; 32], hop_data: &[u8], hmac_byt
680744

681745
let mut chacha = ChaCha20::new(&rho, &[0u8; 8]);
682746
let mut chacha_stream = ChaChaReader { chacha: &mut chacha, read: Cursor::new(&hop_data[..]) };
683-
match <msgs::OnionHopData as Readable>::read(&mut chacha_stream) {
747+
let payload_read_res = if payment_hash.is_some() {
748+
match <msgs::OnionHopData as Readable>::read(&mut chacha_stream) {
749+
Ok(payload) => Ok(Payload::Payment(payload)),
750+
Err(e) => Err(e)
751+
}
752+
} else if encrypted_tlv_ss.is_some() {
753+
match <onion_message::Payload as ReadableArgs<SharedSecret>>::read(&mut chacha_stream, encrypted_tlv_ss.unwrap()) {
754+
Ok(payload) => Ok(Payload::Message(payload)),
755+
Err(e) => Err(e)
756+
}
757+
} else {
758+
unreachable!(); // We already asserted that one of these is `Some`
759+
};
760+
match payload_read_res {
684761
Err(err) => {
685762
let error_code = match err {
686763
msgs::DecodeError::UnknownVersion => 0x4000 | 1, // unknown realm byte
@@ -718,10 +795,17 @@ pub(crate) fn decode_next_hop(shared_secret: [u8; 32], hop_data: &[u8], hmac_byt
718795
chacha_stream.read_exact(&mut next_bytes).unwrap();
719796
assert_ne!(next_bytes[..], [0; 32][..]);
720797
}
721-
return Ok(Hop::Receive(msg));
798+
return Ok((msg, None));
722799
} else {
723-
let mut new_packet_bytes = [0; 20*65];
724-
let read_pos = chacha_stream.read(&mut new_packet_bytes).unwrap();
800+
let (mut new_packet_bytes, read_pos) = if payment_hash.is_some() {
801+
let mut new_packet_bytes = [0 as u8; 20*65];
802+
let read_pos = chacha_stream.read(&mut new_packet_bytes).unwrap();
803+
(NextPacketBytes::Payment(new_packet_bytes), read_pos)
804+
} else {
805+
let mut new_packet_bytes = vec![0 as u8; hop_data.len()];
806+
let read_pos = chacha_stream.read(&mut new_packet_bytes).unwrap();
807+
(NextPacketBytes::Message(new_packet_bytes), read_pos)
808+
};
725809
#[cfg(debug_assertions)]
726810
{
727811
// Check two things:
@@ -733,12 +817,11 @@ pub(crate) fn decode_next_hop(shared_secret: [u8; 32], hop_data: &[u8], hmac_byt
733817
}
734818
// Once we've emptied the set of bytes our peer gave us, encrypt 0 bytes until we
735819
// fill the onion hop data we'll forward to our next-hop peer.
736-
chacha_stream.chacha.process_in_place(&mut new_packet_bytes[read_pos..]);
737-
return Ok(Hop::Forward {
738-
next_hop_data: msg,
739-
next_hop_hmac: hmac,
740-
new_packet_bytes,
741-
})
820+
match new_packet_bytes {
821+
NextPacketBytes::Payment(ref mut bytes) => chacha_stream.chacha.process_in_place(&mut bytes[read_pos..]),
822+
NextPacketBytes::Message(ref mut bytes) => chacha_stream.chacha.process_in_place(&mut bytes[read_pos..]),
823+
}
824+
return Ok((msg, Some((hmac, new_packet_bytes))))
742825
}
743826
},
744827
}

0 commit comments

Comments
 (0)