Skip to content

Commit 4efb006

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 d5c1b32 commit 4efb006

File tree

3 files changed

+223
-20
lines changed

3 files changed

+223
-20
lines changed

lightning/src/ln/channelmanager.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2139,7 +2139,7 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
21392139
}
21402140
}
21412141

2142-
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) {
2142+
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) {
21432143
Ok(res) => res,
21442144
Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
21452145
return_malformed_err!(err_msg, err_code);
@@ -2955,7 +2955,7 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
29552955
let phantom_secret_res = self.keys_manager.get_node_secret(Recipient::PhantomNode);
29562956
if phantom_secret_res.is_ok() && fake_scid::is_valid_phantom(&self.fake_scid_rand_bytes, short_chan_id) {
29572957
let phantom_shared_secret = SharedSecret::new(&onion_packet.public_key.unwrap(), &phantom_secret_res.unwrap()).secret_bytes();
2958-
let next_hop = match onion_utils::decode_next_hop(phantom_shared_secret, &onion_packet.hop_data, onion_packet.hmac, payment_hash) {
2958+
let next_hop = match onion_utils::decode_next_payment_hop(phantom_shared_secret, &onion_packet.hop_data, onion_packet.hmac, payment_hash) {
29592959
Ok(res) => res,
29602960
Err(onion_utils::OnionDecodeErr::Malformed { err_msg, err_code }) => {
29612961
let sha256_of_onion = Sha256::hash(&onion_packet.hop_data).into_inner();

lightning/src/ln/onion_message.rs

Lines changed: 124 additions & 4 deletions
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::{Readable, ReadableArgs, VecWriter, Writeable, Writer};
23+
use util::ser::{FixedLengthReader, Readable, ReadableArgs, VecWriter, Writeable, Writer};
2424

2525
use core::mem;
2626
use core::ops::Deref;
@@ -128,6 +128,40 @@ impl Writeable for (Payload, SharedSecret) {
128128
}
129129
}
130130

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

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

lightning/src/ln/onion_utils.rs

Lines changed: 97 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use routing::gossip::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)