Skip to content

Commit be9206c

Browse files
committed
public static peel_onion method on OnionMessenger
1 parent 989304e commit be9206c

File tree

2 files changed

+109
-78
lines changed

2 files changed

+109
-78
lines changed

lightning/src/onion_message/messenger.rs

+108-77
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,16 @@ pub trait CustomOnionMessageHandler {
246246
fn read_custom_message<R: io::Read>(&self, message_type: u64, buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError>;
247247
}
248248

249+
/// A processed incoming onion message, containing either a Forward (another onion message)
250+
/// or a Receive payload with decrypted contents.
251+
pub enum PeeledOnion<CMH: Deref> where
252+
CMH::Target: CustomOnionMessageHandler,
253+
{
254+
/// Forwarded onion, with the next node id and a new onion
255+
Forward(PublicKey, msgs::OnionMessage),
256+
/// Received onion message, with decrypted contents, path_id, and reply path
257+
Receive(OnionMessageContents<<<CMH as Deref>::Target as CustomOnionMessageHandler>::CustomMessage>, Option<[u8; 32]>, Option<BlindedPath>)
258+
}
249259

250260
/// Create an onion message with contents `message` to the destination of `path`.
251261
/// Returns (introduction_node_id, onion_msg)
@@ -357,6 +367,96 @@ where
357367
}
358368
}
359369

370+
/// Decode one layer of an incoming onion message
371+
/// Returns either a Forward (another onion message), or Receive (decrypted content)
372+
pub fn peel_onion<T: CustomOnionMessageContents>(
373+
node_signer: &NS, secp_ctx: &Secp256k1<secp256k1::All>, logger: &L, custom_handler: &CMH,
374+
msg: &msgs::OnionMessage,
375+
) -> Result<PeeledOnion<CMH>, ()> {
376+
let control_tlvs_ss = match node_signer.ecdh(Recipient::Node, &msg.blinding_point, None) {
377+
Ok(ss) => ss,
378+
Err(e) => {
379+
log_error!(logger, "Failed to retrieve node secret: {:?}", e);
380+
return Err(());
381+
}
382+
};
383+
let onion_decode_ss = {
384+
let blinding_factor = {
385+
let mut hmac = HmacEngine::<Sha256>::new(b"blinded_node_id");
386+
hmac.input(control_tlvs_ss.as_ref());
387+
Hmac::from_engine(hmac).into_inner()
388+
};
389+
match node_signer.ecdh(Recipient::Node, &msg.onion_routing_packet.public_key,
390+
Some(&Scalar::from_be_bytes(blinding_factor).unwrap()))
391+
{
392+
Ok(ss) => ss.secret_bytes(),
393+
Err(()) => {
394+
log_trace!(logger, "Failed to compute onion packet shared secret");
395+
return Err(());
396+
}
397+
}
398+
};
399+
match onion_utils::decode_next_untagged_hop(
400+
onion_decode_ss, &msg.onion_routing_packet.hop_data[..], msg.onion_routing_packet.hmac,
401+
(control_tlvs_ss, custom_handler.deref(), logger.deref())
402+
) {
403+
Ok((Payload::Receive::<<<CMH as Deref>::Target as CustomOnionMessageHandler>::CustomMessage> {
404+
message, control_tlvs: ReceiveControlTlvs::Unblinded(ReceiveTlvs { path_id }), reply_path,
405+
}, None)) => {
406+
Ok(PeeledOnion::Receive(message, path_id, reply_path))
407+
},
408+
Ok((Payload::Forward(ForwardControlTlvs::Unblinded(ForwardTlvs {
409+
next_node_id, next_blinding_override
410+
})), Some((next_hop_hmac, new_packet_bytes)))) => {
411+
// TODO: we need to check whether `next_node_id` is our node, in which case this is a dummy
412+
// blinded hop and this onion message is destined for us. In this situation, we should keep
413+
// unwrapping the onion layers to get to the final payload. Since we don't have the option
414+
// of creating blinded paths with dummy hops currently, we should be ok to not handle this
415+
// for now.
416+
let new_pubkey = match onion_utils::next_hop_pubkey(&secp_ctx, msg.onion_routing_packet.public_key, &onion_decode_ss) {
417+
Ok(pk) => pk,
418+
Err(e) => {
419+
log_trace!(logger, "Failed to compute next hop packet pubkey: {}", e);
420+
return Err(())
421+
}
422+
};
423+
let outgoing_packet = Packet {
424+
version: 0,
425+
public_key: new_pubkey,
426+
hop_data: new_packet_bytes,
427+
hmac: next_hop_hmac,
428+
};
429+
let onion_message = msgs::OnionMessage {
430+
blinding_point: match next_blinding_override {
431+
Some(blinding_point) => blinding_point,
432+
None => {
433+
match onion_utils::next_hop_pubkey(
434+
&secp_ctx, msg.blinding_point, control_tlvs_ss.as_ref()
435+
) {
436+
Ok(bp) => bp,
437+
Err(e) => {
438+
log_trace!(logger, "Failed to compute next blinding point: {}", e);
439+
return Err(())
440+
}
441+
}
442+
}
443+
},
444+
onion_routing_packet: outgoing_packet,
445+
};
446+
447+
Ok(PeeledOnion::Forward(next_node_id, onion_message))
448+
},
449+
Err(e) => {
450+
log_trace!(logger, "Errored decoding onion message packet: {:?}", e);
451+
Err(())
452+
},
453+
_ => {
454+
log_trace!(logger, "Received bogus onion message packet, either the sender encoded a final hop as a forwarding hop or vice versa");
455+
Err(())
456+
},
457+
}
458+
}
459+
360460
fn respond_with_onion_message<T: CustomOnionMessageContents>(
361461
&self, response: OnionMessageContents<T>, path_id: Option<[u8; 32]>,
362462
reply_path: Option<BlindedPath>
@@ -457,40 +557,13 @@ where
457557
/// soon we'll delegate the onion message to a handler that can generate invoices or send
458558
/// payments.
459559
fn handle_onion_message(&self, _peer_node_id: &PublicKey, msg: &msgs::OnionMessage) {
460-
let control_tlvs_ss = match self.node_signer.ecdh(Recipient::Node, &msg.blinding_point, None) {
461-
Ok(ss) => ss,
462-
Err(e) => {
463-
log_error!(self.logger, "Failed to retrieve node secret: {:?}", e);
464-
return
465-
}
466-
};
467-
let onion_decode_ss = {
468-
let blinding_factor = {
469-
let mut hmac = HmacEngine::<Sha256>::new(b"blinded_node_id");
470-
hmac.input(control_tlvs_ss.as_ref());
471-
Hmac::from_engine(hmac).into_inner()
472-
};
473-
match self.node_signer.ecdh(Recipient::Node, &msg.onion_routing_packet.public_key,
474-
Some(&Scalar::from_be_bytes(blinding_factor).unwrap()))
475-
{
476-
Ok(ss) => ss.secret_bytes(),
477-
Err(()) => {
478-
log_trace!(self.logger, "Failed to compute onion packet shared secret");
479-
return
480-
}
481-
}
482-
};
483-
match onion_utils::decode_next_untagged_hop(
484-
onion_decode_ss, &msg.onion_routing_packet.hop_data[..], msg.onion_routing_packet.hmac,
485-
(control_tlvs_ss, &*self.custom_handler, &*self.logger)
560+
match Self::peel_onion::<<<CMH as Deref>::Target as CustomOnionMessageHandler>::CustomMessage>(
561+
&self.node_signer, &self.secp_ctx, &self.logger, &self.custom_handler, msg
486562
) {
487-
Ok((Payload::Receive::<<<CMH as Deref>::Target as CustomOnionMessageHandler>::CustomMessage> {
488-
message, control_tlvs: ReceiveControlTlvs::Unblinded(ReceiveTlvs { path_id }), reply_path,
489-
}, None)) => {
563+
Ok(PeeledOnion::Receive(message, path_id, reply_path)) => {
490564
log_trace!(self.logger,
491565
"Received an onion message with path_id {:02x?} and {} reply_path",
492566
path_id, if reply_path.is_some() { "a" } else { "no" });
493-
494567
let response = match message {
495568
OnionMessageContents::Offers(msg) => {
496569
self.offers_handler.handle_message(msg)
@@ -501,50 +574,11 @@ where
501574
.map(|msg| OnionMessageContents::Custom(msg))
502575
},
503576
};
504-
505577
if let Some(response) = response {
506578
self.respond_with_onion_message(response, path_id, reply_path);
507579
}
508580
},
509-
Ok((Payload::Forward(ForwardControlTlvs::Unblinded(ForwardTlvs {
510-
next_node_id, next_blinding_override
511-
})), Some((next_hop_hmac, new_packet_bytes)))) => {
512-
// TODO: we need to check whether `next_node_id` is our node, in which case this is a dummy
513-
// blinded hop and this onion message is destined for us. In this situation, we should keep
514-
// unwrapping the onion layers to get to the final payload. Since we don't have the option
515-
// of creating blinded paths with dummy hops currently, we should be ok to not handle this
516-
// for now.
517-
let new_pubkey = match onion_utils::next_hop_pubkey(&self.secp_ctx, msg.onion_routing_packet.public_key, &onion_decode_ss) {
518-
Ok(pk) => pk,
519-
Err(e) => {
520-
log_trace!(self.logger, "Failed to compute next hop packet pubkey: {}", e);
521-
return
522-
}
523-
};
524-
let outgoing_packet = Packet {
525-
version: 0,
526-
public_key: new_pubkey,
527-
hop_data: new_packet_bytes,
528-
hmac: next_hop_hmac,
529-
};
530-
let onion_message = msgs::OnionMessage {
531-
blinding_point: match next_blinding_override {
532-
Some(blinding_point) => blinding_point,
533-
None => {
534-
match onion_utils::next_hop_pubkey(
535-
&self.secp_ctx, msg.blinding_point, control_tlvs_ss.as_ref()
536-
) {
537-
Ok(bp) => bp,
538-
Err(e) => {
539-
log_trace!(self.logger, "Failed to compute next blinding point: {}", e);
540-
return
541-
}
542-
}
543-
}
544-
},
545-
onion_routing_packet: outgoing_packet,
546-
};
547-
581+
Ok(PeeledOnion::Forward(next_node_id, onion_message)) => {
548582
let mut pending_per_peer_msgs = self.pending_messages.lock().unwrap();
549583
if outbound_buffer_full(&next_node_id, &pending_per_peer_msgs) {
550584
log_trace!(self.logger, "Dropping forwarded onion message to peer {:?}: outbound buffer full", next_node_id);
@@ -563,15 +597,12 @@ where
563597
e.get_mut().push_back(onion_message);
564598
log_trace!(self.logger, "Forwarding an onion message to peer {}", next_node_id);
565599
}
566-
};
600+
}
567601
},
568602
Err(e) => {
569-
log_trace!(self.logger, "Errored decoding onion message packet: {:?}", e);
570-
},
571-
_ => {
572-
log_trace!(self.logger, "Received bogus onion message packet, either the sender encoded a final hop as a forwarding hop or vice versa");
573-
},
574-
};
603+
log_error!(self.logger, "Failed to process onion message {:?}", e);
604+
}
605+
}
575606
}
576607

577608
fn peer_connected(&self, their_node_id: &PublicKey, init: &msgs::Init, _inbound: bool) -> Result<(), ()> {

lightning/src/onion_message/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ mod packet;
2727
mod functional_tests;
2828

2929
// Re-export structs so they can be imported with just the `onion_message::` module prefix.
30-
pub use self::messenger::{CustomOnionMessageContents, CustomOnionMessageHandler, DefaultMessageRouter, Destination, MessageRouter, OnionMessageContents, OnionMessagePath, OnionMessenger, SendError, SimpleArcOnionMessenger, SimpleRefOnionMessenger};
30+
pub use self::messenger::{CustomOnionMessageContents, CustomOnionMessageHandler, DefaultMessageRouter, Destination, MessageRouter, OnionMessageContents, OnionMessagePath, OnionMessenger, PeeledOnion, SendError, SimpleArcOnionMessenger, SimpleRefOnionMessenger};
3131
pub use self::offers::{OffersMessage, OffersMessageHandler};
3232
pub use self::packet::Packet;
3333
pub(crate) use self::packet::ControlTlvs;

0 commit comments

Comments
 (0)