From 2f53cd25268bb72cc857cbf68757f093385004fd Mon Sep 17 00:00:00 2001 From: Orbital Date: Mon, 28 Aug 2023 16:42:28 -0500 Subject: [PATCH 1/2] Upgrade ldk to 0.0.116 --- Cargo.lock | 4 +-- Cargo.toml | 2 +- src/lnd.rs | 32 +++++++++++++++++++- src/main.rs | 28 +++++++++++++++-- src/onion_messenger.rs | 69 +++++++++++++++++++++++++++++++----------- 5 files changed, 111 insertions(+), 24 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index cef60edb..74bb290c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -609,9 +609,9 @@ checksum = "2b00cc1c228a6782d0f076e7b232802e0c5689d41bb5df366f2a6b6621cfdfe1" [[package]] name = "lightning" -version = "0.0.114" +version = "0.0.116" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "800ec68a160529ba3ca12c5db629867c4a8de2df272792c1246602966a5b789b" +checksum = "90a0f2155316f1570446a0447c993480673f840748c8ed25bbc59dfc442ac770" dependencies = [ "bitcoin", ] diff --git a/Cargo.toml b/Cargo.toml index 3d137636..3892ca44 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,7 @@ spec = "config_spec.toml" async-trait = "0.1.66" bitcoin = { version = "0.29.2", features = ["rand"] } futures = "0.3.26" -lightning = "0.0.114" +lightning = "0.0.116" rand_chacha = "0.3.1" rand_core = "0.6.4" log = "0.4.17" diff --git a/src/lnd.rs b/src/lnd.rs index f5deabda..d011fa2e 100644 --- a/src/lnd.rs +++ b/src/lnd.rs @@ -1,12 +1,15 @@ use bitcoin::bech32::u5; +use bitcoin::network::constants::Network; use bitcoin::secp256k1::ecdh::SharedSecret; use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature}; use bitcoin::secp256k1::{self, PublicKey, Scalar, Secp256k1}; use futures::executor::block_on; -use lightning::chain::keysinterface::{KeyMaterial, NodeSigner, Recipient}; use lightning::ln::msgs::UnsignedGossipMessage; +use lightning::sign::{KeyMaterial, NodeSigner, Recipient}; use std::cell::RefCell; use std::collections::HashMap; +use std::error::Error; +use std::fmt; use std::path::PathBuf; use tonic_lnd::{Client, ConnectError}; @@ -132,3 +135,30 @@ impl<'a> NodeSigner for LndNodeSigner<'a> { unimplemented!("not required for onion messaging"); } } + +#[derive(Debug)] +/// Error when parsing provided configuration options. +pub(crate) enum NetworkParseError { + /// Invalid indicates an invalid network was provided. + Invalid(String), +} + +impl Error for NetworkParseError {} + +impl fmt::Display for NetworkParseError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + NetworkParseError::Invalid(network_str) => write!(f, "invalid network provided: {network_str}. Should be mainnet, testnet, signet, or regtest."), + } + } +} + +pub(crate) fn string_to_network(network_str: &str) -> Result { + match network_str { + "mainnet" => Ok(Network::Bitcoin), + "testnet" => Ok(Network::Testnet), + "signet" => Ok(Network::Signet), + "regtest" => Ok(Network::Regtest), + _ => Err(NetworkParseError::Invalid(network_str.to_string())), + } +} diff --git a/src/main.rs b/src/main.rs index d3bb73af..1729d060 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,13 +15,15 @@ mod internal { #[macro_use] extern crate configure_me; -use crate::lnd::{features_support_onion_messages, get_lnd_client, LndCfg, LndNodeSigner}; +use crate::lnd::{ + features_support_onion_messages, get_lnd_client, string_to_network, LndCfg, LndNodeSigner, +}; use crate::onion_messenger::{run_onion_messenger, MessengerUtilities}; use bitcoin::secp256k1::PublicKey; use internal::*; use lightning::ln::peer_handler::IgnoringMessageHandler; -use lightning::onion_message::OnionMessenger; +use lightning::onion_message::{DefaultMessageRouter, OnionMessenger}; use log::{error, info}; use std::collections::HashMap; use std::str::FromStr; @@ -45,6 +47,18 @@ async fn main() -> Result<(), ()> { .expect("failed to get info") .into_inner(); + let mut network_str = None; + for chain in info.chains { + if chain.chain == "bitcoin" { + network_str = Some(chain.network.clone()) + } + } + if network_str.is_none() { + error!("lnd node is not connected to bitcoin network as expected"); + return Err(()); + } + let network = string_to_network(&network_str.unwrap()); + let pubkey = PublicKey::from_str(&info.identity_pubkey).unwrap(); info!("Starting lndk for node: {pubkey}."); @@ -80,11 +94,19 @@ async fn main() -> Result<(), ()> { &messenger_utils, &node_signer, &messenger_utils, + &DefaultMessageRouter {}, + IgnoringMessageHandler {}, IgnoringMessageHandler {}, ); let mut peers_client = client.lightning().clone(); - run_onion_messenger(peer_support, &mut peers_client, onion_messenger).await + run_onion_messenger( + peer_support, + &mut peers_client, + onion_messenger, + network.unwrap(), + ) + .await } #[cfg(test)] diff --git a/src/onion_messenger.rs b/src/onion_messenger.rs index 52821a40..6b653913 100644 --- a/src/onion_messenger.rs +++ b/src/onion_messenger.rs @@ -2,13 +2,17 @@ use crate::clock::TokioClock; use crate::lnd::{features_support_onion_messages, ONION_MESSAGES_OPTIONAL}; use crate::rate_limit::{RateLimiter, TokenLimiter}; use async_trait::async_trait; +use bitcoin::blockdata::constants::ChainHash; +use bitcoin::network::constants::Network; use bitcoin::secp256k1::PublicKey; use core::ops::Deref; -use lightning::chain::keysinterface::EntropySource; -use lightning::chain::keysinterface::NodeSigner; use lightning::ln::features::InitFeatures; use lightning::ln::msgs::{Init, OnionMessage, OnionMessageHandler}; -use lightning::onion_message::{CustomOnionMessageHandler, OnionMessenger}; +use lightning::onion_message::{ + CustomOnionMessageHandler, MessageRouter, OffersMessageHandler, OnionMessenger, +}; +use lightning::sign::EntropySource; +use lightning::sign::NodeSigner; use lightning::util::logger::{Level, Logger, Record}; use lightning::util::ser::{Readable, Writeable}; use log::{debug, error, info, trace, warn}; @@ -95,15 +99,25 @@ impl Logger for MessengerUtilities { /// 3. Outgoing Poll: Using a simple ticker, produces polling events to check for outgoing onion messages. /// /// The main consumer processes one MessengerEvent at a time, applying basic rate limiting to each peer to prevent spam. -pub(crate) async fn run_onion_messenger( +pub(crate) async fn run_onion_messenger< + ES: Deref, + NS: Deref, + L: Deref, + MR: Deref, + OMH: Deref, + CMH: Deref, +>( current_peers: HashMap, ln_client: &mut tonic_lnd::LightningClient, - onion_messenger: OnionMessenger, + onion_messenger: OnionMessenger, + network: Network, ) -> Result<(), ()> where ES::Target: EntropySource, NS::Target: NodeSigner, L::Target: Logger, + MR::Target: MessageRouter, + OMH::Target: OffersMessageHandler, CMH::Target: CustomOnionMessageHandler + Sized, { // Setup channels that we'll use to communicate onion messenger events. We buffer our channels by the number of @@ -201,9 +215,14 @@ where let mut message_sender = CustomMessenger { client: ln_client.clone(), }; - let consume_result = - consume_messenger_events(onion_messenger, receiver, &mut message_sender, rate_limiter) - .await; + let consume_result = consume_messenger_events( + onion_messenger, + receiver, + &mut message_sender, + rate_limiter, + network, + ) + .await; match consume_result { Ok(_) => info!("Consume messenger events exited."), Err(e) => error!("Consume messenger events exited: {e}."), @@ -520,7 +539,10 @@ async fn consume_messenger_events( mut events: Receiver, message_sender: &mut impl SendCustomMessage, rate_limiter: &mut impl RateLimiter, + network: Network, ) -> Result<(), ConsumerError> { + let network = vec![ChainHash::using_genesis_block(network)]; + while let Some(onion_event) = events.recv().await { match onion_event { // We don't want to log SendOutgoing events, since we send out this event every 100 ms. @@ -543,6 +565,7 @@ async fn consume_messenger_events( &Init { features: init_features, remote_network_address: None, + networks: Some(network.clone()), }, false, ) @@ -677,11 +700,12 @@ async fn relay_outgoing_msg_event( mod tests { use super::*; use crate::tests::test_utils::pubkey; + use bitcoin::network::constants::Network; use bitcoin::secp256k1::PublicKey; use bytes::BufMut; + use lightning::events::OnionMessageProvider; use lightning::ln::features::{InitFeatures, NodeFeatures}; use lightning::ln::msgs::{OnionMessage, OnionMessageHandler}; - use lightning::util::events::OnionMessageProvider; use lightning::util::ser::Readable; use lightning::util::ser::Writeable; use mockall::mock; @@ -858,10 +882,15 @@ mod tests { .await .unwrap(); - let consume_err = - consume_messenger_events(mock, receiver, &mut sender_mock, &mut rate_limiter) - .await - .expect_err("consume should error"); + let consume_err = consume_messenger_events( + mock, + receiver, + &mut sender_mock, + &mut rate_limiter, + Network::Regtest, + ) + .await + .expect_err("consume should error"); matches!(consume_err, ConsumerError::PeerProducerExit); } @@ -882,10 +911,15 @@ mod tests { let mut sender_mock = MockSendCustomMessenger::new(); - let consume_err = - consume_messenger_events(mock, receiver, &mut sender_mock, &mut rate_limiter) - .await - .expect_err("consume should error"); + let consume_err = consume_messenger_events( + mock, + receiver, + &mut sender_mock, + &mut rate_limiter, + Network::Regtest, + ) + .await + .expect_err("consume should error"); matches!(consume_err, ConsumerError::OnionMessengerFailure); } @@ -903,6 +937,7 @@ mod tests { receiver_done, &mut sender_mock, &mut rate_limiter, + Network::Regtest, ) .await .is_ok()); From 56d75f6897cd6aa162a76d5693eb7fa5feca493c Mon Sep 17 00:00:00 2001 From: Orbital Date: Mon, 28 Aug 2023 18:10:33 -0500 Subject: [PATCH 2/2] Add .cargo ignore advisory We can safely ignore the "RUSTSEC-2023-0052" advisory while tonic_lnd comes up with a fix. --- .cargo/audit.toml | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 .cargo/audit.toml diff --git a/.cargo/audit.toml b/.cargo/audit.toml new file mode 100644 index 00000000..d7063fda --- /dev/null +++ b/.cargo/audit.toml @@ -0,0 +1,2 @@ +[advisories] +ignore = ["RUSTSEC-2023-0052"]