Add baseline OnionMessenger and msgs::OnionMessage and its serialization
authorValentine Wallace <vwallace@protonmail.com>
Wed, 22 Jun 2022 21:03:06 +0000 (17:03 -0400)
committerValentine Wallace <vwallace@protonmail.com>
Tue, 2 Aug 2022 23:17:26 +0000 (19:17 -0400)
OnionMessenger will be hooked up to the PeerManager to send and receive OMs in
a follow-up PR.

lightning/src/ln/msgs.rs
lightning/src/onion_message/messenger.rs [new file with mode: 0644]
lightning/src/onion_message/mod.rs

index 424dbafe6612f54f12a6c77c4755a0312311b169..950d6a35947ae27d28e8e02a3d71d92d4dd8450d 100644 (file)
@@ -32,6 +32,7 @@ use bitcoin::hash_types::{Txid, BlockHash};
 
 use ln::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
 use ln::onion_utils;
+use onion_message;
 
 use prelude::*;
 use core::fmt;
@@ -41,7 +42,7 @@ use io_extras::read_to_end;
 
 use util::events::MessageSendEventsProvider;
 use util::logger;
-use util::ser::{Readable, Writeable, Writer, FixedLengthReader, HighZeroBytesDroppedVarInt, Hostname};
+use util::ser::{LengthReadable, Readable, Writeable, Writer, FixedLengthReader, HighZeroBytesDroppedVarInt, Hostname};
 
 use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
 
@@ -305,6 +306,14 @@ pub struct UpdateAddHTLC {
        pub(crate) onion_routing_packet: OnionPacket,
 }
 
+ /// An onion message to be sent or received from a peer
+#[derive(Clone, Debug, PartialEq)]
+pub struct OnionMessage {
+       /// Used in decrypting the onion packet's payload.
+       pub blinding_point: PublicKey,
+       pub(crate) onion_routing_packet: onion_message::Packet,
+}
+
 /// An update_fulfill_htlc message to be sent or received from a peer
 #[derive(Clone, Debug, PartialEq)]
 pub struct UpdateFulfillHTLC {
@@ -1340,6 +1349,29 @@ impl_writeable_msg!(UpdateAddHTLC, {
        onion_routing_packet
 }, {});
 
+impl Readable for OnionMessage {
+       fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
+               let blinding_point: PublicKey = Readable::read(r)?;
+               let len: u16 = Readable::read(r)?;
+               let mut packet_reader = FixedLengthReader::new(r, len as u64);
+               let onion_routing_packet: onion_message::Packet = <onion_message::Packet as LengthReadable>::read(&mut packet_reader)?;
+               Ok(Self {
+                       blinding_point,
+                       onion_routing_packet,
+               })
+       }
+}
+
+impl Writeable for OnionMessage {
+       fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
+               self.blinding_point.write(w)?;
+               let onion_packet_len = self.onion_routing_packet.serialized_length();
+               (onion_packet_len as u16).write(w)?;
+               self.onion_routing_packet.write(w)?;
+               Ok(())
+       }
+}
+
 impl Writeable for FinalOnionHopData {
        fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
                self.payment_secret.0.write(w)?;
diff --git a/lightning/src/onion_message/messenger.rs b/lightning/src/onion_message/messenger.rs
new file mode 100644 (file)
index 0000000..e2d7b51
--- /dev/null
@@ -0,0 +1,71 @@
+// This file is Copyright its original authors, visible in version control
+// history.
+//
+// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
+// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
+// You may not use this file except in accordance with one or both of these
+// licenses.
+
+//! LDK sends, receives, and forwards onion messages via the [`OnionMessenger`]. See its docs for
+//! more information.
+
+use bitcoin::secp256k1::{self, PublicKey, Secp256k1};
+
+use chain::keysinterface::{InMemorySigner, KeysInterface, KeysManager, Sign};
+use ln::msgs;
+use util::logger::Logger;
+
+use core::ops::Deref;
+use sync::{Arc, Mutex};
+use prelude::*;
+
+/// A sender, receiver and forwarder of onion messages. In upcoming releases, this object will be
+/// used to retrieve invoices and fulfill invoice requests from [offers].
+///
+/// [offers]: <https://github.com/lightning/bolts/pull/798>
+pub struct OnionMessenger<Signer: Sign, K: Deref, L: Deref>
+       where K::Target: KeysInterface<Signer = Signer>,
+             L::Target: Logger,
+{
+       keys_manager: K,
+       logger: L,
+       pending_messages: Mutex<HashMap<PublicKey, Vec<msgs::OnionMessage>>>,
+       secp_ctx: Secp256k1<secp256k1::All>,
+       // Coming soon:
+       // invoice_handler: InvoiceHandler,
+       // custom_handler: CustomHandler, // handles custom onion messages
+}
+
+impl<Signer: Sign, K: Deref, L: Deref> OnionMessenger<Signer, K, L>
+       where K::Target: KeysInterface<Signer = Signer>,
+             L::Target: Logger,
+{
+       /// Constructs a new `OnionMessenger` to send, forward, and delegate received onion messages to
+       /// their respective handlers.
+       pub fn new(keys_manager: K, logger: L) -> Self {
+               let mut secp_ctx = Secp256k1::new();
+               secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
+               OnionMessenger {
+                       keys_manager,
+                       pending_messages: Mutex::new(HashMap::new()),
+                       secp_ctx,
+                       logger,
+               }
+       }
+}
+
+// TODO: parameterize the below Simple* types with OnionMessenger and handle the messages it
+// produces
+/// Useful for simplifying the parameters of [`SimpleArcChannelManager`] and
+/// [`SimpleArcPeerManager`]. See their docs for more details.
+///
+///[`SimpleArcChannelManager`]: crate::ln::channelmanager::SimpleArcChannelManager
+///[`SimpleArcPeerManager`]: crate::ln::peer_handler::SimpleArcPeerManager
+pub type SimpleArcOnionMessenger<L> = OnionMessenger<InMemorySigner, Arc<KeysManager>, Arc<L>>;
+/// Useful for simplifying the parameters of [`SimpleRefChannelManager`] and
+/// [`SimpleRefPeerManager`]. See their docs for more details.
+///
+///[`SimpleRefChannelManager`]: crate::ln::channelmanager::SimpleRefChannelManager
+///[`SimpleRefPeerManager`]: crate::ln::peer_handler::SimpleRefPeerManager
+pub type SimpleRefOnionMessenger<'a, 'b, L> = OnionMessenger<InMemorySigner, &'a KeysManager, &'b L>;
index 37858c1a4a68d8e1541b4e5720606b0f4d81296b..291030f4e26c5ce7b9eccee6e33760debab430fe 100644 (file)
 //! Onion Messages: sending, receiving, forwarding, and ancillary utilities live here
 
 mod blinded_route;
+mod messenger;
 mod packet;
 mod utils;
 
 // Re-export structs so they can be imported with just the `onion_message::` module prefix.
 pub use self::blinded_route::{BlindedRoute, BlindedHop};
+pub use self::messenger::{OnionMessenger, SimpleArcOnionMessenger, SimpleRefOnionMessenger};
+pub(crate) use self::packet::Packet;