Skip to content

Commit

Permalink
Merge pull request #69 from lndk-org/ldk-0.0.116-upgrade
Browse files Browse the repository at this point in the history
Upgrade to ldk 0.0.116
  • Loading branch information
orbitalturtle authored Aug 29, 2023
2 parents 4562d0a + 56d75f6 commit 0de819a
Show file tree
Hide file tree
Showing 6 changed files with 113 additions and 24 deletions.
2 changes: 2 additions & 0 deletions .cargo/audit.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[advisories]
ignore = ["RUSTSEC-2023-0052"]
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
32 changes: 31 additions & 1 deletion src/lnd.rs
Original file line number Diff line number Diff line change
@@ -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};

Expand Down Expand Up @@ -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<Network, NetworkParseError> {
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())),
}
}
28 changes: 25 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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}.");

Expand Down Expand Up @@ -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)]
Expand Down
69 changes: 52 additions & 17 deletions src/onion_messenger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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<ES: Deref, NS: Deref, L: Deref, CMH: Deref>(
pub(crate) async fn run_onion_messenger<
ES: Deref,
NS: Deref,
L: Deref,
MR: Deref,
OMH: Deref,
CMH: Deref,
>(
current_peers: HashMap<PublicKey, bool>,
ln_client: &mut tonic_lnd::LightningClient,
onion_messenger: OnionMessenger<ES, NS, L, CMH>,
onion_messenger: OnionMessenger<ES, NS, L, MR, OMH, CMH>,
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
Expand Down Expand Up @@ -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}."),
Expand Down Expand Up @@ -520,7 +539,10 @@ async fn consume_messenger_events(
mut events: Receiver<MessengerEvents>,
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.
Expand All @@ -543,6 +565,7 @@ async fn consume_messenger_events(
&Init {
features: init_features,
remote_network_address: None,
networks: Some(network.clone()),
},
false,
)
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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);
}

Expand All @@ -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);
}

Expand All @@ -903,6 +937,7 @@ mod tests {
receiver_done,
&mut sender_mock,
&mut rate_limiter,
Network::Regtest,
)
.await
.is_ok());
Expand Down

0 comments on commit 0de819a

Please sign in to comment.