Skip to content

Commit

Permalink
OTHER CHANGES FOR CONNECTING TO INTRODUCTION PEER
Browse files Browse the repository at this point in the history
  • Loading branch information
orbitalturtle committed Feb 1, 2024
1 parent d2021ae commit a1a2cd5
Show file tree
Hide file tree
Showing 6 changed files with 154 additions and 34 deletions.
1 change: 0 additions & 1 deletion 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 @@ -35,7 +35,7 @@ triggered = "0.1.2"
bitcoincore-rpc = { package="core-rpc", version = "0.17.0" }
bitcoind = { version = "0.30.0", features = [ "22_0" ] }
chrono = { version = "0.4.26" }
ldk-sample = { git = "https://github.com/lndk-org/ldk-sample", branch = "offer-handling" }
ldk-sample = { path = "../ldk-sample" }
mockall = "0.11.3"
tempfile = "3.5.0"

Expand Down
5 changes: 5 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,14 @@ use triggered::{Listener, Trigger};

static INIT: Once = Once::new();

#[derive(Clone)]
pub struct Cfg {
pub lnd: LndCfg,
pub log_dir: Option<String>,
pub signals: Signals,
}

#[derive(Clone)]
pub struct Signals {
// Use to externally trigger shutdown.
pub shutdown: Trigger,
Expand Down Expand Up @@ -208,12 +210,15 @@ impl OfferHandler {
blinded_path: BlindedPath,
reply_path: Option<BlindedPath>,
) -> Result<(), OfferError<Secp256k1Error>> {
println!("WAITING FOR PAY OFFER SIGNAL");
// Wait for onion messenger to give us the signal that it's ready. Once the onion messenger drops
// the channel sender, recv will return None and we'll stop blocking here.
while (self.started.borrow_mut().recv().await).is_some() {
println!("Error: we shouldn't receive any messages on this channel");
}

println!("WE BE GETTING PAST PAY OFFER WAIT");

let validated_amount = validate_amount(&offer, amount).await?;

// For now we connect directly to the introduction node of the blinded path so we don't need any
Expand Down
3 changes: 3 additions & 0 deletions src/lndk_offers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@ pub async fn connect_to_peer(
let node_id_str = node_id.to_string();
for peer in resp.peers.iter() {
if peer.pub_key == node_id_str {
println!("ALREADY CONNECTED TO PEER");
return Ok(());
}
}
Expand All @@ -193,6 +194,8 @@ pub async fn connect_to_peer(
.await
.map_err(OfferError::PeerConnectError)?;

println!("FOUND NODE IN GRAPH: {:?}", node);

let node = match node {
Some(node) => node,
None => return Err(OfferError::NodeAddressNotFound),
Expand Down
38 changes: 33 additions & 5 deletions tests/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use chrono::Utc;
use ldk_sample::config::LdkUserInfo;
use ldk_sample::node_api::Node as LdkNode;
use lightning::util::logger::Level;
use std::net::SocketAddr;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::thread;
Expand All @@ -35,28 +35,32 @@ pub async fn setup_test_infrastructure(

let connect_params = bitcoind.node.params.get_cookie_values().unwrap();

let port = get_available_port().unwrap();
let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), port);
let ldk1_config = LdkUserInfo {
bitcoind_rpc_username: connect_params.0.clone().unwrap(),
bitcoind_rpc_password: connect_params.1.clone().unwrap(),
bitcoind_rpc_host: String::from("localhost"),
bitcoind_rpc_port: bitcoind.node.params.rpc_socket.port(),
ldk_data_dir: ldk_test_dir.clone(),
ldk_announced_listen_addr: Vec::new(),
ldk_peer_listening_port: get_available_port().unwrap(),
ldk_announced_listen_addr: vec![addr.into()],
ldk_peer_listening_port: port,
ldk_announced_node_name: [0; 32],
network: Network::Regtest,
log_level: Level::Trace,
node_num: 1,
};

let port = get_available_port().unwrap();
let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), port);
let ldk2_config = LdkUserInfo {
bitcoind_rpc_username: connect_params.0.unwrap(),
bitcoind_rpc_password: connect_params.1.unwrap(),
bitcoind_rpc_host: String::from("localhost"),
bitcoind_rpc_port: bitcoind.node.params.rpc_socket.port(),
ldk_data_dir: ldk_test_dir,
ldk_announced_listen_addr: Vec::new(),
ldk_peer_listening_port: get_available_port().unwrap(),
ldk_announced_listen_addr: vec![addr.into()],
ldk_peer_listening_port: port,
ldk_announced_node_name: [0; 32],
network: Network::Regtest,
log_level: Level::Trace,
Expand Down Expand Up @@ -415,4 +419,28 @@ impl LndNode {
sleep(Duration::from_secs(2)).await;
}
}

pub async fn describe_graph(
&mut self,
) -> tonic_lnd::lnrpc::ChannelGraph {
let disconnect_req = tonic_lnd::lnrpc::ChannelGraphRequest {
..Default::default()
};

let resp = if let Some(client) = self.client.clone() {
let make_request = || async {
client
.clone()
.lightning()
.describe_graph(disconnect_req.clone())
.await
};
let resp = test_utils::retry_async(make_request, String::from("describe_graph"));
resp.await.unwrap()
} else {
panic!("No client")
};

resp
}
}
139 changes: 112 additions & 27 deletions tests/integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,15 @@ use lndk;

use bitcoin::secp256k1::{PublicKey, Secp256k1};
use bitcoin::Network;
use bitcoincore_rpc::bitcoin::Network as RpcNetwork;
use bitcoincore_rpc::RpcApi;
use chrono::Utc;
use ldk_sample::node_api::Node as LdkNode;
use lightning::blinded_path::BlindedPath;
use lightning::offers::offer::Quantity;
use lndk::onion_messenger::MessengerUtilities;
use lndk::Signals;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::str::FromStr;
use std::time::SystemTime;
Expand Down Expand Up @@ -112,22 +115,75 @@ async fn test_lndk_forwards_onion_message() {
// invoice_request and sends it.
async fn test_lndk_send_invoice_request() {
let test_name = "lndk_send_invoice_request";
let (_bitcoind, mut lnd, ldk1, ldk2, lndk_dir) =
let (bitcoind, mut lnd, ldk1, ldk2, lndk_dir) =
common::setup_test_infrastructure(test_name).await;

// Here we'll produce a little network path:
// Here we'll produce a little network of channels:
//
// ldk1 <-> ldk2 <-> lnd
//
// ldk1 will be the offer creator, which will build a blinded route from ldk2 to ldk1.
let (pubkey, _) = ldk1.get_node_info();
let (pubkey, addr) = ldk1.get_node_info();
let (pubkey_2, addr_2) = ldk2.get_node_info();
let lnd_info = lnd.get_info().await;
let lnd_pubkey = PublicKey::from_str(&lnd_info.identity_pubkey).unwrap();

ldk1.connect_to_peer(pubkey_2, addr_2).await.unwrap();
lnd.connect_to_peer(pubkey_2, addr_2).await;

let ldk2_fund_addr = ldk2.bitcoind_client.get_new_address().await;
//let lnd_fund_addr = lnd.new_address().await.address;

// We need to convert funding addresses to the form that the bitcoincore_rpc library recognizes.
let ldk2_addr_string = ldk2_fund_addr.to_string();
let ldk2_addr = bitcoind::bitcoincore_rpc::bitcoin::Address::from_str(&ldk2_addr_string)
.unwrap()
.require_network(RpcNetwork::Regtest)
.unwrap();
//let lnd_addr = bitcoind::bitcoincore_rpc::bitcoin::Address::from_str(&lnd_fund_addr)
// .unwrap()
// .require_network(RpcNetwork::Regtest)
// .unwrap();
//let lnd_network_addr = lnd
// .address
// .replace("localhost", "127.0.0.1")
// .replace("https://", "");

// Fund both of these nodes, open the channels, and synchronize the network.
bitcoind
.node
.client
.generate_to_address(6, &ldk2_addr)
.unwrap();

lnd.wait_for_chain_sync().await;

ldk2.open_channel(pubkey, addr, 200000, 0, true)
.await
.unwrap();

lnd.wait_for_graph_sync().await;

//ldk2.open_channel(
// lnd_pubkey,
// SocketAddr::from_str(&lnd_network_addr).unwrap(),
// 200000,
// 10000000,
// true,
//)
//.await
//.unwrap();

//lnd.wait_for_graph_sync().await;

bitcoind
.node
.client
.generate_to_address(20, &ldk2_addr)
.unwrap();

lnd.wait_for_chain_sync().await;

let path_pubkeys = vec![pubkey_2, pubkey];
let expiration = SystemTime::now() + Duration::from_secs(24 * 60 * 60);
let offer = ldk1
Expand Down Expand Up @@ -156,7 +212,7 @@ async fn test_lndk_send_invoice_request() {
};

let lndk_cfg = lndk::Cfg {
lnd: lnd_cfg,
lnd: lnd_cfg.clone(),
log_dir: Some(
lndk_dir
.join(format!("lndk-logs.txt"))
Expand All @@ -182,34 +238,63 @@ async fn test_lndk_send_invoice_request() {
panic!("lndk should not have completed first {:?}", val);
},
// We wait for ldk2 to receive the onion message.
res = messenger.offer_handler.pay_offer(offer.clone(), Some(20_000), Network::Regtest, client.clone(), blinded_path.clone(), Some(reply_path)) => {
res = messenger.offer_handler.pay_offer(offer.clone(), Some(20_000), Network::Regtest, client.clone(), blinded_path.clone(), Some(reply_path.clone())) => {
assert!(res.is_ok());
shutdown.trigger();
ldk1.stop().await;
ldk2.stop().await;
println!("ERM");
//shutdown.trigger();
//ldk1.stop().await;
//ldk2.stop().await;
}
}

//// Let's try it again, but, make sure we can pay an offer when the LND node is not already connected
//// to the introduction node (LDK2).
//lnd.disconnect_peer(pubkey_2).await;
println!("WE BE GETTING DOWN HERE???");

// Let's try again, but, make sure we can request the invoice when the LND node is not already connected
// to the introduction node (LDK2).
lnd.disconnect_peer(pubkey_2).await;

//sleep(Duration::from_secs(5)).await;
sleep(Duration::from_secs(10)).await;

lnd.wait_for_graph_sync().await;

//let resp = lnd.describe_graph().await;
//println!("GRAPHHHHHHH: {:?}", resp);

//let handler = &mut lndk::OfferHandler::new();
//select! {
// val = handler.run(lndk_cfg) => {
// panic!("lndk should not have completed first {:?}", val);
// },
// // We wait for ldk2 to receive the onion message.
// res = handler.pay_offer(offer, Some(20_000), Network::Regtest, client, blinded_path) => {
// assert!(res.is_ok());
// shutdown.trigger();
// ldk1.stop().await;
// ldk2.stop().await;
// }
//}
//println!("DESCRIBE GRAPH: {:#?}", resp);

let (shutdown, listener) = triggered::trigger();
let (tx, rx): (Sender<u32>, Receiver<u32>) = mpsc::channel(1);
let signals = Signals {
shutdown: shutdown.clone(),
listener,
started: tx,
};
let lndk_cfg = lndk::Cfg {
lnd: lnd_cfg,
log_dir: Some(
lndk_dir
.join(format!("lndk-logs.txt"))
.to_str()
.unwrap()
.to_string(),
),
signals,
};

let handler = lndk::OfferHandler::new(rx);
let messenger = lndk::LndkOnionMessenger::new(handler);
select! {
val = messenger.run(lndk_cfg) => {
panic!("lndk should not have completed first {:?}", val);
},
// We wait for ldk2 to receive the onion message.
res = messenger.offer_handler.pay_offer(offer, Some(20_000), Network::Regtest, client, blinded_path, Some(reply_path)) => {
//if let Err(e) = res {
// println!("ERR: {e:?}");
//};

assert!(res.is_ok());
shutdown.trigger();
ldk1.stop().await;
ldk2.stop().await;
}
}
}

0 comments on commit a1a2cd5

Please sign in to comment.