Skip to content

Commit

Permalink
Fixing Secp256k1 dependencies
Browse files Browse the repository at this point in the history
  • Loading branch information
dr-orlovsky committed Jun 5, 2020
1 parent dd7006c commit 13238d7
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 66 deletions.
14 changes: 6 additions & 8 deletions src/lnp/peer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,21 @@
//! BOLT-1. Manages state of the remote peer and handles direct communications
//! with it. Relies on transport layer (BOLT-8-based) protocol.
use lightning::secp256k1;
use bitcoin::secp256k1;

use super::transport::*;


pub struct Peer {
pub node: NodeAddr,
connection: Connection,
awaiting_pong: bool,
}

impl Peer {
pub async fn new_outbound(node: NodeAddr,
private_key: &secp256k1::SecretKey,
ephemeral_private_key: &secp256k1::SecretKey
pub async fn new_outbound(
node: NodeAddr,
private_key: &secp256k1::SecretKey,
ephemeral_private_key: &secp256k1::SecretKey,
) -> Result<Self, ConnectionError> {
let connection = node.connect(private_key, ephemeral_private_key).await?;
Ok(Self {
Expand All @@ -55,6 +55,4 @@ pub struct Message {
pub extension: TLV,
}

pub trait Messageable: From<Message> + Into<Message> {

}
pub trait Messageable: From<Message> + Into<Message> {}
125 changes: 67 additions & 58 deletions src/lnp/transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,50 +14,58 @@
//! BOLT-8 related structures and functions covering Lightning network
//! transport layer
use std::io;
use std::convert::TryInto;
use std::fmt;
use std::str::FromStr;
use std::io;
use std::net::SocketAddr;
use std::convert::TryInto;
use std::str::FromStr;

#[cfg(feature="use-tokio")]
use tokio::net::TcpStream;
#[cfg(feature="use-tokio")]
use tokio::io::AsyncWriteExt;
#[cfg(feature="use-tokio")]
use tokio::io::AsyncReadExt;
#[cfg(feature = "serde")]
use serde::{Serialize, Deserialize};
use serde::{Deserialize, Serialize};
#[cfg(feature = "use-tokio")]
use tokio::io::AsyncReadExt;
#[cfg(feature = "use-tokio")]
use tokio::io::AsyncWriteExt;
#[cfg(feature = "use-tokio")]
use tokio::net::TcpStream;

#[cfg(not(feature="use-tokio"))]
use std::net::TcpStream;
#[cfg(not(feature="use-tokio"))]
#[cfg(not(feature = "use-tokio"))]
use std::io::{Read, Write};
#[cfg(not(feature = "use-tokio"))]
use std::net::TcpStream;

use lightning::secp256k1;
use bitcoin::secp256k1;

// We re-export this under more proper name (it's not per-channel encryptor,
// it is per-connection transport-level encryptor)
use lightning::ln::peers::conduit::Conduit as Encryptor;
use lightning::ln::peers::handshake::PeerHandshake;

use crate::common::internet::InetSocketAddr;
use super::LIGHTNING_P2P_DEFAULT_PORT;

use crate::common::internet::InetSocketAddr;

pub const MAX_TRANSPORT_FRAME_SIZE: usize = 65569;

#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(try_from = "crate::common::serde::CowHelper", into = "String", crate = "serde_crate"))]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(
try_from = "crate::common::serde::CowHelper",
into = "String",
crate = "serde_crate"
)
)]
pub struct NodeAddr {
pub node_id: secp256k1::PublicKey,
pub inet_addr: InetSocketAddr,
}

impl NodeAddr {
pub async fn connect(&self,
private_key: &secp256k1::SecretKey,
ephemeral_private_key: &secp256k1::SecretKey
pub async fn connect(
&self,
private_key: &secp256k1::SecretKey,
ephemeral_private_key: &secp256k1::SecretKey,
) -> Result<Connection, ConnectionError> {
Connection::new(self, private_key, ephemeral_private_key).await
}
Expand All @@ -81,20 +89,19 @@ impl FromStr for NodeAddr {
let mut splitter = s.split('@');
let (id, inet) = match (splitter.next(), splitter.next(), splitter.next()) {
(Some(id), Some(inet), None) => (id, inet),
_ => Err(String::from(err_msg))?
_ => Err(String::from(err_msg))?,
};

let mut splitter = inet.split(':');
let (addr, port) = match (splitter.next(), splitter.next(), splitter.next()) {
(Some(addr), Some(port), None) =>
(addr, port.parse().map_err(|_| err_msg)?),
(Some(addr), Some(port), None) => (addr, port.parse().map_err(|_| err_msg)?),
(Some(addr), None, _) => (addr, LIGHTNING_P2P_DEFAULT_PORT),
_ => Err(String::from(err_msg))?
_ => Err(String::from(err_msg))?,
};

Ok(Self {
node_id: id.parse().map_err(|_| err_msg)?,
inet_addr: InetSocketAddr::new(addr.parse().map_err(|_| err_msg)?, port)
inet_addr: InetSocketAddr::new(addr.parse().map_err(|_| err_msg)?, port),
})
}
}
Expand All @@ -107,7 +114,7 @@ impl_into_stringly_standard!(NodeAddr);
pub enum ConnectionError {
TorNotYetSupported,
FailedHandshake(String),
IoError(io::Error)
IoError(io::Error),
}

impl From<io::Error> for ConnectionError {
Expand All @@ -116,102 +123,104 @@ impl From<io::Error> for ConnectionError {
}
}


pub struct Connection {
pub stream: TcpStream,
pub outbound: bool,
encryptor: Encryptor,
}

impl Connection {
pub async fn new(node: &NodeAddr,
private_key: &secp256k1::SecretKey,
ephemeral_private_key: &secp256k1::SecretKey
pub async fn new(
node: &NodeAddr,
private_key: &secp256k1::SecretKey,
ephemeral_private_key: &secp256k1::SecretKey,
) -> Result<Self, ConnectionError> {

// TODO: Add support for Tor connections
if node.inet_addr.address.is_tor() {
Err(ConnectionError::TorNotYetSupported)?
}

#[cfg(feature="use-log")]
#[cfg(feature = "use-log")]
debug!("Initiating connection protocol with {}", node);

// Opening network connection
#[cfg(feature="use-tor")]
let socket_addr: SocketAddr = node.inet_addr.try_into()
#[cfg(feature = "use-tor")]
let socket_addr: SocketAddr = node
.inet_addr
.try_into()
.map_err(|_| ConnectionError::TorNotYetSupported)?;
#[cfg(not(feature="use-tor"))]
let socket_addr: SocketAddr = node.inet_addr.try_into()
#[cfg(not(feature = "use-tor"))]
let socket_addr: SocketAddr = node
.inet_addr
.try_into()
.expect("We are not using tor so conversion of internet addresses must not fail");

#[cfg(feature="use-log")]
#[cfg(feature = "use-log")]
trace!("Connecting to {}", socket_addr);
#[cfg(feature="use-tokio")]
#[cfg(feature = "use-tokio")]
let mut stream = TcpStream::connect(socket_addr).await?;
#[cfg(not(feature="use-tokio"))]
#[cfg(not(feature = "use-tokio"))]
let mut stream = TcpStream::connect(socket_addr)?;

#[cfg(feature="use-log")]
#[cfg(feature = "use-log")]
trace!("Starting handshake procedure with {}", node);
let mut handshake = PeerHandshake::new_outbound(
private_key, &node.node_id, ephemeral_private_key
);
let mut handshake =
PeerHandshake::new_outbound(private_key, &node.node_id, ephemeral_private_key);

let mut step: usize = 0;
let mut input: &[u8] = &[];
let mut buf = vec![];
buf.reserve(MAX_TRANSPORT_FRAME_SIZE);
let result: Result<Encryptor, ConnectionError> = loop {
#[cfg(feature="use-log")]
#[cfg(feature = "use-log")]
trace!("Handshake step {}: processing data `{:x?}`", step, input);

let (act, enc) = handshake.process_act(input)
let (act, enc) = handshake
.process_act(input)
.map_err(|msg| ConnectionError::FailedHandshake(msg))?;

if let Some(encryptor) = enc {
break Ok(encryptor)
break Ok(encryptor);
} else if let Some(act) = act {
#[cfg(feature="use-log")]
#[cfg(feature = "use-log")]
trace!("Handshake step {}: sending `{:x?}`", step, act.serialize());

#[cfg(feature="use-tokio")]
#[cfg(feature = "use-tokio")]
stream.write_all(&act.serialize()).await?;
#[cfg(not(feature="use-tokio"))]
#[cfg(not(feature = "use-tokio"))]
stream.write_all(&act.serialize())?;
} else {
#[cfg(feature="use-log")]
#[cfg(feature = "use-log")]
error!("`PeerHandshake.process_act` returned non-standard result");

Err(ConnectionError::FailedHandshake(
"PeerHandshake.process_act returned non-standard result"
.to_string()
"PeerHandshake.process_act returned non-standard result".to_string(),
))?
}

#[cfg(feature="use-log")]
#[cfg(feature = "use-log")]
trace!("Handshake step {}: waiting for response`", step);

#[cfg(feature="use-tokio")]
#[cfg(feature = "use-tokio")]
let read_len = stream.read_buf(&mut buf).await?;
#[cfg(not(feature="use-tokio"))]
#[cfg(not(feature = "use-tokio"))]
let read_len = stream.read_to_end(&mut buf)?;
input = &buf[0..read_len];

#[cfg(feature="use-log")]
#[cfg(feature = "use-log")]
trace!("Handshake step {}: received data `{:x?}`", step, input);

step += 1;
};
let encryptor = result?;

#[cfg(feature="use-log")]
#[cfg(feature = "use-log")]
trace!("Handshake successfully completed");

Ok(Self {
stream,
outbound: true,
encryptor
encryptor,
})
}
}

0 comments on commit 13238d7

Please sign in to comment.