Skip to content

Commit

Permalink
fix: connect peer and open channel
Browse files Browse the repository at this point in the history
  • Loading branch information
thesimplekid committed Jul 17, 2023
1 parent 318ea03 commit 10cceea
Show file tree
Hide file tree
Showing 8 changed files with 177 additions and 98 deletions.
18 changes: 14 additions & 4 deletions mint-manager/src/components/channels.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
use std::collections::HashMap;

use anyhow::Result;
use bitcoin::secp256k1::PublicKey;
use gloo_net::http::Request;
use node_manager_types::responses::{self, ChannelInfo};
use serde_json::Value;
use url::Url;
use yew::platform::spawn_local;
use yew::prelude::*;
Expand Down Expand Up @@ -36,7 +40,7 @@ enum View {
pub struct Channels {
view: View,
channels: Vec<ChannelInfo>,
peers: Vec<responses::PeerInfo>,
peers: HashMap<PublicKey, responses::PeerInfo>,
}

impl Component for Channels {
Expand All @@ -51,7 +55,7 @@ impl Component for Channels {
let url = ctx.props().url.clone();
spawn_local(async move {
get_channels(&jwt, &url, channels_callback).await.ok();
get_peers(&jwt, &url, peers_callback).await.ok();
get_peers(&jwt, &url, peers_callback).await.unwrap();
});

Self::default()
Expand All @@ -72,6 +76,10 @@ impl Component for Channels {
true
}
Msg::FetechedPeers(peers) => {
let peers = peers.into_iter().fold(HashMap::new(), |mut acc, x| {
acc.insert(x.peer_pubkey, x);
acc
});
self.peers = peers;
true
}
Expand Down Expand Up @@ -161,14 +169,16 @@ async fn get_peers(
got_peers_cb: Callback<Vec<responses::PeerInfo>>,
) -> Result<()> {
let url = url.join("peers")?;
let fetched_channels: Vec<responses::PeerInfo> = Request::get(url.as_str())
let fetched_channels: Value = Request::get(url.as_str())
.header("Authorization", &format!("Bearer {}", jwt))
.send()
.await?
.json()
.await?;

got_peers_cb.emit(fetched_channels);
let peers = serde_json::from_value(fetched_channels)?;

got_peers_cb.emit(peers);

Ok(())
}
4 changes: 2 additions & 2 deletions mint-manager/src/components/on_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ impl Component for OnChain {
<button class="px-6 py-2 rounded-sm shadow-sm dark:bg-violet-400 dark:text-gray-900" onclick={pay}>{"Send"}</button>
<button class="px-6 py-2 rounded-sm" onclick={close.clone()}>{"Back"}</button>
</div>
</>
</>

}
}
Expand All @@ -218,7 +218,7 @@ impl Component for OnChain {
<button class="px-6 py-2 rounded-sm" onclick={close.clone()}>{"Back"}</button>
// <button class="px-6 py-2 rounded-sm shadow-sm dark:bg-violet-400 dark:text-gray-900">{"Copy"}</button>
</div>
</>
</>

}
}
Expand Down
205 changes: 117 additions & 88 deletions mint-manager/src/components/open_channel.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::collections::HashMap;
use std::str::FromStr;

use anyhow::Result;
Expand Down Expand Up @@ -54,7 +55,7 @@ async fn get_peers(
pub struct Props {
pub jwt: String,
pub url: Url,
pub peers: Vec<responses::PeerInfo>,
pub peers: HashMap<PublicKey, responses::PeerInfo>,
pub back_callback: Callback<MouseEvent>,
}

Expand All @@ -64,10 +65,16 @@ pub enum Msg {
FetechedPeers(Vec<responses::PeerInfo>),
}

#[derive(Default)]
enum View {
#[default]
OpenChannel,
OpenedChannel,
}

#[derive(Default)]
pub struct OpenChannel {
host_input_node_ref: NodeRef,
port_input_node_ref: NodeRef,
view: View,
amount_input_node_ref: NodeRef,
push_amount_input_node_ref: NodeRef,
select_node_ref: NodeRef,
Expand All @@ -83,7 +90,9 @@ impl Component for OpenChannel {
let jwt = ctx.props().jwt.clone();
let url = ctx.props().url.clone();
spawn_local(async move {
get_peers(&jwt, &url, callback).await.unwrap();
if let Err(err) = get_peers(&jwt, &url, callback).await {
warn!("Could not get peers: {:?}", err);
}
});
Self::default()
}
Expand All @@ -98,16 +107,6 @@ impl Component for OpenChannel {
.cast::<HtmlSelectElement>()
.map(|p| PublicKey::from_str(&p.value()));

let host = self
.host_input_node_ref
.cast::<HtmlInputElement>()
.map(|i| i.value());

let port = self
.port_input_node_ref
.cast::<HtmlInputElement>()
.map(|i| i.value().parse::<u16>());

let amount = self
.amount_input_node_ref
.cast::<HtmlInputElement>()
Expand All @@ -124,45 +123,52 @@ impl Component for OpenChannel {
value.parse::<u64>()
});

if let (
Some(Ok(public_key)),
Some(host),
Some(Ok(port)),
Some(Ok(amount)),
Some(Ok(push_amount)),
) = (pubkey, host, port, amount, push_amount)
if let (Some(Ok(public_key)), Some(Ok(amount)), Some(Ok(push_amount))) =
(pubkey, amount, push_amount)
{
let amount = Amount::from_sat(amount);
let push_amount = if push_amount > 0 {
Some(Amount::from_sat(push_amount))
if let Some(peer) = ctx.props().peers.get(&public_key) {
let host = peer.host.clone();
let port = peer.port;

let amount = Amount::from_sat(amount);
let push_amount = if push_amount > 0 {
Some(Amount::from_sat(push_amount))
} else {
None
};

let open_channel = OpenChannelRequest {
public_key,
host,
port,
amount,
push_amount,
};

let callback = ctx.link().callback(Msg::ChannelOpened);
let jwt = ctx.props().jwt.clone();
let url = ctx.props().url.clone();

spawn_local(async move {
if let Err(err) =
post_open_channel(&jwt, &url, open_channel, callback).await
{
warn!("Failed to open channel: {:?}", err);
}
});
} else {
None
};

let open_channel = OpenChannelRequest {
public_key,
host,
port,
amount,
push_amount,
};

let callback = ctx.link().callback(Msg::ChannelOpened);
let jwt = ctx.props().jwt.clone();
let url = ctx.props().url.clone();

spawn_local(async move {
post_open_channel(&jwt, &url, open_channel, callback)
.await
.ok();
});
warn!("Peer is missing");
}
} else {
warn!("Sommethitng is missing");
warn!("Something is missing");
}

false
}
Msg::ChannelOpened(_response) => false,
Msg::ChannelOpened(_response) => {
self.view = View::OpenedChannel;
true
}
Msg::FetechedPeers(peers) => {
self.peers = peers;
true
Expand All @@ -174,47 +180,70 @@ impl Component for OpenChannel {
let on_submit = ctx.link().callback(|_| Msg::Submit);

html! {

<>

<a class="block flex-1 p-6 bg-white border border-gray-200 rounded-lg shadow hover:bg-gray-100 dark:bg-gray-800 dark:border-gray-700 dark:hover:bg-gray-700">
<h5 class="mb-2 text-2xl font-bold tracking-tight text-gray-900 dark:text-white"> { "Open Channel" } </h5>
<div>
<div class="relative z-0 w-full mb-6 group">
</div>
</div>
<div class="relative z-0 w-full mb-6 group">

<select
ref={self.select_node_ref.clone()}
class="block py-2.5 px-0 w-full text-sm text-gray-900 bg-transparent border-0 border-b-2 border-gray-300 appearance-none dark:text-white dark:border-gray-600 dark:focus:border-blue-500 focus:outline-none focus:ring-0 focus:border-blue-600 peer"
>
<option value="" disabled=true>
{ "Select Peer" }
</option>
{ for self.peers.iter().map(|p| {html!{
<option value={p.peer_pubkey.to_string()} >
{ p.peer_pubkey }
</option>
}

}
) }
</select>
</div>

<div class="relative z-0 w-full mb-6 group">
<input type="numeric" name="channel_size" id="channel_size" class="block py-2.5 px-0 w-full text-sm text-gray-900 bg-transparent border-0 border-b-2 border-gray-300 appearance-none dark:text-white dark:border-gray-600 dark:focus:border-blue-500 focus:outline-none focus:ring-0 focus:border-blue-600 peer" ref={self.amount_input_node_ref.clone()} />
<label for="channel_size" class="peer-focus:font-medium absolute text-sm text-gray-500 dark:text-gray-400 duration-300 transform -translate-y-6 scale-75 top-3 -z-10 origin-[0] peer-focus:left-0 peer-focus:text-blue-600 peer-focus:dark:text-blue-500 peer-placeholder-shown:scale-100 peer-placeholder-shown:translate-y-0 peer-focus:scale-75 peer-focus:-translate-y-6">{"Channel Size (sat)"}</label>
</div>
<div class="relative z-0 w-full mb-6 group">
<input type="numeric" name="push_amount" id="push_amount" class="block py-2.5 px-0 w-full text-sm text-gray-900 bg-transparent border-0 border-b-2 border-gray-300 appearance-none dark:text-white dark:border-gray-600 dark:focus:border-blue-500 focus:outline-none focus:ring-0 focus:border-blue-600 peer" ref={self.push_amount_input_node_ref.clone()} />
<label for="push_amount" class="peer-focus:font-medium absolute text-sm text-gray-500 dark:text-gray-400 duration-300 transform -translate-y-6 scale-75 top-3 -z-10 origin-[0] peer-focus:left-0 peer-focus:text-blue-600 peer-focus:dark:text-blue-500 peer-placeholder-shown:scale-100 peer-placeholder-shown:translate-y-0 peer-focus:scale-75 peer-focus:-translate-y-6">{"Push Amount"}</label>
</div>
<button class="px-6 py-2 rounded-sm shadow-sm dark:bg-violet-400 dark:text-gray-900" onclick={on_submit}>{"Open Channel"}</button>
<button class="px-6 py-2 rounded-sm" onclick={ctx.props().back_callback.clone()}>{"Back"}</button>
</a>
</>
}
<>
<a class="block flex-1 p-6 bg-white border border-gray-200 rounded-lg shadow hover:bg-gray-100 dark:bg-gray-800 dark:border-gray-700 dark:hover:bg-gray-700">
<h5 class="mb-2 text-2xl font-bold tracking-tight text-gray-900 dark:text-white"> { "Open Channel" } </h5>
{
match self.view {
View::OpenChannel => {
html! {
<>
<div class="relative z-0 w-full mb-6 group">
</div>
<div class="relative z-0 w-full mb-6 group">
<select
ref={self.select_node_ref.clone()}
class="block py-2.5 px-0 w-full text-sm text-gray-900 bg-transparent border-0 border-b-2 border-gray-300 appearance-none dark:text-white dark:border-gray-600 dark:focus:border-blue-500 focus:outline-none focus:ring-0 focus:border-blue-600 peer"
>
<option value="" disabled=true>
{ "Select Peer" }
</option>
{ for self.peers.iter().map(|p| {
html! {
<option value={p.peer_pubkey.to_string()}>
{ p.peer_pubkey }
</option>
}
})}
</select>
</div>
<div class="relative z-0 w-full mb-6 group">
<input
type="numeric"
name="channel_size"
id="channel_size"
class="block py-2.5 px-0 w-full text-sm text-gray-900 bg-transparent border-0 border-b-2 border-gray-300 appearance-none dark:text-white dark:border-gray-600 dark:focus:border-blue-500 focus:outline-none focus:ring-0 focus:border-blue-600 peer"
ref={self.amount_input_node_ref.clone()}
/>
<label for="channel_size" class="peer-focus:font-medium absolute text-sm text-gray-500 dark:text-gray-400 duration-300 transform -translate-y-6 scale-75 top-3 -z-10 origin-[0] peer-focus:left-0 peer-focus:text-blue-600 peer-focus:dark:text-blue-500 peer-placeholder-shown:scale-100 peer-placeholder-shown:translate-y-0 peer-focus:scale-75 peer-focus:-translate-y-6">{"Channel Size (sat)"}</label>
</div>
<div class="relative z-0 w-full mb-6 group">
<input
type="numeric"
name="push_amount"
id="push_amount"
class="block py-2.5 px-0 w-full text-sm text-gray-900 bg-transparent border-0 border-b-2 border-gray-300 appearance-none dark:text-white dark:border-gray-600 dark:focus:border-blue-500 focus:outline-none focus:ring-0 focus:border-blue-600 peer"
ref={self.push_amount_input_node_ref.clone()}
/>
<label for="push_amount" class="peer-focus:font-medium absolute text-sm text-gray-500 dark:text-gray-400 duration-300 transform -translate-y-6 scale-75 top-3 -z-10 origin-[0] peer-focus:left-0 peer-focus:text-blue-600 peer-focus:dark:text-blue-500 peer-placeholder-shown:scale-100 peer-placeholder-shown:translate-y-0 peer-focus:scale-75 peer-focus:-translate-y-6">{"Push Amount"}</label>
</div>
<button class="px-6 py-2 rounded-sm shadow-sm dark:bg-violet-400 dark:text-gray-900" onclick={on_submit}>{"Open Channel"}</button>
<button class="px-6 py-2 rounded-sm" onclick={ctx.props().back_callback.clone()}>{"Back"}</button>
</>
}
}
View::OpenedChannel => {
html! {
<>
<h5 class="mb-2 text-2xl font-bold tracking-tight text-gray-900 dark:text-white"> { "Channel Opened" } </h5>
<button class="px-6 py-2 rounded-sm" onclick={ctx.props().back_callback.clone()}>{"Back"}</button>
</>
}
}
}
}
</a>
</>
}
}
}
19 changes: 18 additions & 1 deletion mint/src/ln/cln.rs
Original file line number Diff line number Diff line change
Expand Up @@ -536,7 +536,7 @@ impl LnNodeManager for Cln {
let cln_response = cln_client
.call(cln_rpc::Request::Connect(cln_rpc::model::ConnectRequest {
id: public_key.to_string(),
host: Some(host),
host: Some(host.clone()),
port: Some(port),
}))
.await?;
Expand All @@ -552,6 +552,8 @@ impl LnNodeManager for Cln {

let peer_info = responses::PeerInfo {
peer_pubkey: public_key,
host,
port,
connected: true,
};

Expand Down Expand Up @@ -622,8 +624,23 @@ fn from_peer_to_info(peer: &ListpeersPeers) -> Result<responses::PeerInfo, Error

let connected = peer.connected;

debug!("{:?}", peer);

let remote_addr: Vec<String> = peer
.clone()
.netaddr
.ok_or(Error::Custom("No net address".to_string()))?[0]
.split(":")
.map(|s| s.to_string())
.collect();

let host = remote_addr[0].to_string();
let port = remote_addr[1].parse::<u16>()?;

Ok(responses::PeerInfo {
peer_pubkey,
host,
port,
connected,
})
}
Expand Down
6 changes: 6 additions & 0 deletions mint/src/ln/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,12 @@ impl From<hex::FromHexError> for Error {
}
}

impl From<std::num::ParseIntError> for Error {
fn from(err: std::num::ParseIntError) -> Self {
Self::Custom(err.to_string())
}
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ErrorResponse {
code: u16,
Expand Down
Loading

0 comments on commit 10cceea

Please sign in to comment.