Skip to content

Commit 48c41d7

Browse files
f jeff feedback
1 parent 4281a68 commit 48c41d7

File tree

6 files changed

+76
-54
lines changed

6 files changed

+76
-54
lines changed

lightning/src/ln/peer_handler.rs

+17-4
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,11 @@ use ln::features::{InitFeatures, NodeFeatures};
2121
use ln::msgs;
2222
use ln::msgs::{ChannelMessageHandler, LightningError, NetAddress, OnionMessageHandler, RoutingMessageHandler};
2323
use ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager};
24-
use util::ser::{VecWriter, Writeable, Writer};
24+
use util::ser::{MaybeReadableArgs, VecWriter, Writeable, Writer};
2525
use ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
2626
use ln::wire;
2727
use ln::wire::Encode;
28-
use onion_message::{CustomOnionMessageHandler, SimpleArcOnionMessenger, SimpleRefOnionMessenger};
28+
use onion_message::{CustomOnionMessageHandler, OnionMessageContents, SimpleArcOnionMessenger, SimpleRefOnionMessenger};
2929
use routing::gossip::{NetworkGraph, P2PGossipSync};
3030
use util::atomic_counter::AtomicCounter;
3131
use util::crypto::sign;
@@ -96,9 +96,22 @@ impl OnionMessageHandler for IgnoringMessageHandler {
9696
}
9797
}
9898
impl CustomOnionMessageHandler for IgnoringMessageHandler {
99-
type CustomMessage = ();
100-
fn handle_custom_message(&self, _msg: Self::CustomMessage) {}
99+
type CustomMessage = Infallible;
100+
fn handle_custom_message(&self, _msg: Self::CustomMessage) {
101+
// Since we always return `None` in the read the handle method should never be called.
102+
unreachable!();
103+
}
104+
}
105+
impl MaybeReadableArgs<u64> for Infallible {
106+
fn read<R: io::Read>(_buffer: &mut R, _msg_type: u64) -> Result<Option<Self>, msgs::DecodeError> where Self: Sized {
107+
Ok(None)
108+
}
101109
}
110+
111+
impl OnionMessageContents for Infallible {
112+
fn tlv_type(&self) -> u64 { unreachable!(); }
113+
}
114+
102115
impl Deref for IgnoringMessageHandler {
103116
type Target = IgnoringMessageHandler;
104117
fn deref(&self) -> &Self { self }

lightning/src/onion_message/functional_tests.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,9 @@
1212
use chain::keysinterface::{KeysInterface, Recipient};
1313
use ln::features::InitFeatures;
1414
use ln::msgs::{self, DecodeError, OnionMessageHandler};
15-
use super::{BlindedRoute, CustomOnionMessageHandler, CustomMessageReadable, Destination, Message, OnionMessageContents, OnionMessenger, SendError};
15+
use super::{BlindedRoute, CustomOnionMessageHandler, Destination, Message, OnionMessageContents, OnionMessenger, SendError};
1616
use util::enforcing_trait_impls::EnforcingSigner;
17-
use util::ser::{Writeable, Writer};
17+
use util::ser::{MaybeReadableArgs, Writeable, Writer};
1818
use util::test_utils;
1919

2020
use bitcoin::network::constants::Network;
@@ -54,8 +54,8 @@ impl Writeable for TestCustomMessage {
5454
}
5555
}
5656

57-
impl CustomMessageReadable for TestCustomMessage {
58-
fn read<R: io::Read>(message_type: u64, buffer: &mut R) -> Result<Option<Self>, DecodeError> where Self: Sized {
57+
impl MaybeReadableArgs<u64> for TestCustomMessage {
58+
fn read<R: io::Read>(buffer: &mut R, message_type: u64) -> Result<Option<Self>, DecodeError> where Self: Sized {
5959
if message_type == CUSTOM_MESSAGE_TYPE {
6060
let mut buf = Vec::new();
6161
buffer.read_to_end(&mut buf)?;

lightning/src/onion_message/messenger.rs

+30-8
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ use ln::msgs::{self, OnionMessageHandler};
2121
use ln::onion_utils;
2222
use ln::peer_handler::IgnoringMessageHandler;
2323
use super::blinded_route::{BlindedRoute, ForwardTlvs, ReceiveTlvs};
24-
pub use super::packet::{CustomMessageReadable, Message, OnionMessageContents};
24+
pub use super::packet::{Message, OnionMessageContents};
2525
use super::packet::{BIG_PACKET_HOP_DATA_LEN, ForwardControlTlvs, Packet, Payload, ReceiveControlTlvs, SMALL_PACKET_HOP_DATA_LEN};
2626
use super::utils;
2727
use util::events::OnionMessageProvider;
@@ -43,9 +43,12 @@ use prelude::*;
4343
/// # use bitcoin::hashes::_export::_core::time::Duration;
4444
/// # use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
4545
/// # use lightning::chain::keysinterface::{InMemorySigner, KeysManager, KeysInterface};
46+
/// # use lightning::ln::msgs::DecodeError;
4647
/// # use lightning::ln::peer_handler::IgnoringMessageHandler;
47-
/// # use lightning::onion_message::{BlindedRoute, Destination, Message, OnionMessenger};
48+
/// # use lightning::onion_message::{BlindedRoute, Destination, Message, OnionMessageContents, OnionMessenger};
4849
/// # use lightning::util::logger::{Logger, Record};
50+
/// # use lightning::util::ser::{MaybeReadableArgs, Writeable, Writer};
51+
/// # use std::io;
4952
/// # use std::sync::Arc;
5053
/// # struct FakeLogger {};
5154
/// # impl Logger for FakeLogger {
@@ -58,18 +61,36 @@ use prelude::*;
5861
/// # let node_secret = SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
5962
/// # let secp_ctx = Secp256k1::new();
6063
/// # let hop_node_id1 = PublicKey::from_secret_key(&secp_ctx, &node_secret);
61-
/// # let (hop_node_id2, hop_node_id3, hop_node_id4) = (hop_node_id1, hop_node_id1,
62-
/// hop_node_id1);
64+
/// # let (hop_node_id2, hop_node_id3, hop_node_id4) = (hop_node_id1, hop_node_id1, hop_node_id1);
6365
/// # let destination_node_id = hop_node_id1;
6466
/// # let your_custom_message_handler = IgnoringMessageHandler {};
6567
/// // Create the onion messenger. This must use the same `keys_manager` as is passed to your
6668
/// // ChannelManager.
6769
/// let onion_messenger = OnionMessenger::new(&keys_manager, logger, your_custom_message_handler);
6870
///
69-
/// // Send an custom onion message to a node id.
71+
/// # struct YourCustomMessage {}
72+
/// impl Writeable for YourCustomMessage {
73+
/// fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
74+
/// # Ok(())
75+
/// // Write your custom onion message to `w`
76+
/// }
77+
/// }
78+
/// impl OnionMessageContents for YourCustomMessage {
79+
/// fn tlv_type(&self) -> u64 {
80+
/// # let your_custom_message_type = 42;
81+
/// your_custom_message_type
82+
/// }
83+
/// }
84+
/// impl MaybeReadableArgs<u64> for YourCustomMessage {
85+
/// fn read<R: io::Read>(r: &mut R, message_type: u64) -> Result<Option<Self>, DecodeError> {
86+
/// # unreachable!()
87+
/// // Read your custom onion message from `r`
88+
/// }
89+
/// }
90+
/// // Send a custom onion message to a node id.
7091
/// let intermediate_hops = [hop_node_id1, hop_node_id2];
7192
/// let reply_path = None;
72-
/// # let your_custom_message = ();
93+
/// # let your_custom_message = YourCustomMessage {};
7394
/// let message = Message::Custom(your_custom_message);
7495
/// onion_messenger.send_onion_message(&intermediate_hops, Destination::Node(destination_node_id), message, reply_path);
7596
///
@@ -81,6 +102,7 @@ use prelude::*;
81102
/// // Send a custom onion message to a blinded route.
82103
/// # let intermediate_hops = [hop_node_id1, hop_node_id2];
83104
/// let reply_path = None;
105+
/// # let your_custom_message = YourCustomMessage {};
84106
/// let message = Message::Custom(your_custom_message);
85107
/// onion_messenger.send_onion_message(&intermediate_hops, Destination::BlindedRoute(blinded_route), message, reply_path);
86108
/// ```
@@ -419,8 +441,8 @@ pub type SimpleRefOnionMessenger<'a, 'b, L> = OnionMessenger<InMemorySigner, &'a
419441
/// Construct onion packet payloads and keys for sending an onion message along the given
420442
/// `unblinded_path` to the given `destination`.
421443
fn packet_payloads_and_keys<T: OnionMessageContents, S: secp256k1::Signing + secp256k1::Verification>(
422-
secp_ctx: &Secp256k1<S>, unblinded_path: &[PublicKey], destination: Destination, message:
423-
Message<T>, mut reply_path: Option<BlindedRoute>, session_priv: &SecretKey
444+
secp_ctx: &Secp256k1<S>, unblinded_path: &[PublicKey], destination: Destination,
445+
message: Message<T>, mut reply_path: Option<BlindedRoute>, session_priv: &SecretKey
424446
) -> Result<(Vec<(Payload<T>, [u8; 32])>, Vec<onion_utils::OnionKeys>), secp256k1::Error> {
425447
let num_hops = unblinded_path.len() + destination.num_hops();
426448
let mut payloads = Vec::with_capacity(num_hops);

lightning/src/onion_message/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -29,5 +29,5 @@ mod functional_tests;
2929

3030
// Re-export structs so they can be imported with just the `onion_message::` module prefix.
3131
pub use self::blinded_route::{BlindedRoute, BlindedHop};
32-
pub use self::messenger::{CustomOnionMessageHandler, CustomMessageReadable, Destination, Message, OnionMessageContents, OnionMessenger, SendError, SimpleArcOnionMessenger, SimpleRefOnionMessenger};
32+
pub use self::messenger::{CustomOnionMessageHandler, Destination, Message, OnionMessageContents, OnionMessenger, SendError, SimpleArcOnionMessenger, SimpleRefOnionMessenger};
3333
pub(crate) use self::packet::Packet;

lightning/src/onion_message/packet.rs

+16-37
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use ln::msgs::DecodeError;
1616
use ln::onion_utils;
1717
use super::blinded_route::{BlindedRoute, ForwardTlvs, ReceiveTlvs};
1818
use util::chacha20poly1305rfc::{ChaChaPolyReadAdapter, ChaChaPolyWriteAdapter};
19-
use util::ser::{BigSize, FixedLengthReader, LengthRead, LengthReadable, LengthReadableArgs, Readable, ReadableArgs, Writeable, Writer};
19+
use util::ser::{BigSize, FixedLengthReader, LengthRead, LengthReadable, LengthReadableArgs, MaybeReadableArgs, Readable, ReadableArgs, Writeable, Writer};
2020

2121
use core::cmp;
2222
use io::{self, Read};
@@ -103,15 +103,6 @@ pub(super) enum Payload<T: OnionMessageContents> {
103103
}
104104
}
105105

106-
/// Trait to be implemented by custom onion messages.
107-
pub trait CustomMessageReadable {
108-
/// Decodes a custom message given the message type. If the given message type is known to the
109-
/// implementation and the message could be decoded, must return `Ok(Some(message))`. If the
110-
/// message type is unknown to the implementation, must return `Ok(None)`. If a decoding error
111-
/// occur, must return `Err(DecodeError::X)` where `X` details the encountered error.
112-
fn read<R: io::Read>(message_type: u64, buffer: &mut R) -> Result<Option<Self>, DecodeError> where Self: Sized;
113-
}
114-
115106
#[derive(Debug)]
116107
/// The contents of an onion message. In the context of offers, this would be the invoice, invoice
117108
/// request, or invoice error.
@@ -142,21 +133,11 @@ impl<T: OnionMessageContents> Writeable for Message<T> {
142133
}
143134

144135
/// Defines a type identifier for encoding an onion message's contents.
145-
pub trait OnionMessageContents: Writeable + CustomMessageReadable {
136+
pub trait OnionMessageContents: Writeable + MaybeReadableArgs<u64> {
146137
/// Returns the type identifying the message payload.
147138
fn tlv_type(&self) -> u64;
148139
}
149140

150-
impl CustomMessageReadable for () {
151-
fn read<R: io::Read>(_message_type: u64, _buffer: &mut R) -> Result<Option<Self>, DecodeError> where Self: Sized {
152-
Ok(None)
153-
}
154-
}
155-
156-
impl OnionMessageContents for () {
157-
fn tlv_type(&self) -> u64 { u64::max_value() }
158-
}
159-
160141
/// Forward control TLVs in their blinded and unblinded form.
161142
pub(super) enum ForwardControlTlvs {
162143
/// If we're sending to a blinded route, the node that constructed the blinded route has provided
@@ -223,27 +204,25 @@ impl<T: OnionMessageContents> ReadableArgs<SharedSecret> for Payload<T> {
223204
let mut reply_path: Option<BlindedRoute> = None;
224205
let mut read_adapter: Option<ChaChaPolyReadAdapter<ControlTlvs>> = None;
225206
let rho = onion_utils::gen_rho_from_shared_secret(&encrypted_tlvs_ss.secret_bytes());
226-
let (mut message_type, mut message) = (None, None);
207+
let mut message_type: Option<u64> = None;
208+
let mut message = None;
227209
decode_tlv_stream!(&mut rd, {
228210
(2, reply_path, option),
229211
(4, read_adapter, (option: LengthReadableArgs, rho)),
230212
}, |msg_type, msg_reader| {
231-
if msg_type >= 64 {
232-
// Don't allow reading more than one data TLV from an onion message.
233-
if message.is_some() || message_type.is_some() {
234-
return Err(DecodeError::InvalidValue)
235-
}
236-
message_type = Some(msg_type);
237-
match T::read(msg_type, msg_reader) {
238-
Ok(Some(msg)) => {
239-
message = Some(msg);
240-
return Ok(true)
241-
},
242-
Ok(None) => return Ok(false),
243-
Err(e) => return Err(e),
244-
}
213+
if msg_type < 64 { return Ok(false) }
214+
// Don't allow reading more than one data TLV from an onion message.
215+
if message_type.is_some() { return Err(DecodeError::InvalidValue) }
216+
217+
message_type = Some(msg_type);
218+
match T::read(msg_reader, msg_type) {
219+
Ok(Some(msg)) => {
220+
message = Some(msg);
221+
Ok(true)
222+
},
223+
Ok(None) => Ok(false),
224+
Err(e) => Err(e),
245225
}
246-
Ok(false)
247226
});
248227
rd.eat_remaining().map_err(|_| DecodeError::ShortRead)?;
249228

lightning/src/util/ser.rs

+8
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,14 @@ impl<T: Readable> MaybeReadable for T {
269269
}
270270
}
271271

272+
/// A trait that various rust-lightning types implement allowing them to (maybe) be read in from a Read, given some additional set of arguments which is required to deserialize.
273+
///
274+
/// (C-not exported) as we only export serialization to/from byte arrays instead
275+
pub trait MaybeReadableArgs<P> {
276+
/// Reads a Self in from the given Read
277+
fn read<R: Read>(reader: &mut R, params: P) -> Result<Option<Self>, DecodeError> where Self: Sized;
278+
}
279+
272280
pub(crate) struct OptionDeserWrapper<T: Readable>(pub Option<T>);
273281
impl<T: Readable> Readable for OptionDeserWrapper<T> {
274282
#[inline]

0 commit comments

Comments
 (0)