From c1d93d073d2133c575e5030e0039634c1f73b295 Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Sun, 29 Jul 2018 15:06:42 +1000 Subject: [PATCH] Tidy up p2p code somewhat --- src/main.rs | 27 ++++++---------------- src/p2p/config.rs | 17 ++++++++++++++ src/p2p/floodsub.rs | 13 +++++------ src/p2p/keys.rs | 41 +++++---------------------------- src/p2p/mod.rs | 9 +++++++- src/p2p/state.rs | 55 +++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 99 insertions(+), 63 deletions(-) create mode 100644 src/p2p/config.rs create mode 100644 src/p2p/state.rs diff --git a/src/main.rs b/src/main.rs index eb458c83f..f84ee672b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -10,14 +10,11 @@ pub mod pubkeystore; pub mod state; pub mod utils; -use p2p::keys; -use p2p::floodsub; use slog::Drain; use clap::{ App, SubCommand}; -use std::sync::Arc; -use std::time::Duration; -use libp2p_peerstore::{ PeerAccess, Peerstore }; -use libp2p_peerstore::memory_peerstore::MemoryPeerstore; +use p2p::config::NetworkConfig; +use p2p::floodsub; +use p2p::state::NetworkState; fn main() { let decorator = slog_term::TermDecorator::new().build(); @@ -33,22 +30,12 @@ fn main() { .about("Generates a new set of random keys for p2p dev.") .get_matches(); + let config = NetworkConfig::default(); if let Some(_) = matches.subcommand_matches("generate-keys") { - keys::generate_keys(&log).expect("Failed to generate keys"); + // keys::generate_keys(&log).expect("Failed to generate keys"); } else { - let (s256k1_public, _s256k1_secret) = keys::load_local_keys(&log); - let peer_id = keys::peer_id_from_pub_key(&s256k1_public); - let bootstrap_peer_id = - keys::peer_id_from_pub_key(&keys::load_bootstrap_pk(&log)); - - let peer_store = Arc::new(MemoryPeerstore::empty()); - - peer_store.peer_or_create(&bootstrap_peer_id).add_addr( - "/ip4/127.0.0.1/tcp/10101/ws".parse().unwrap(), - Duration::from_secs(3600 * 24 * 356) - ); - - floodsub::listen(peer_id, peer_store, &log); + let state = NetworkState::new(&config).expect("setup failed"); + floodsub::listen(state, &log); } info!(log, "Exiting."); } diff --git a/src/p2p/config.rs b/src/p2p/config.rs new file mode 100644 index 000000000..5f1556f2f --- /dev/null +++ b/src/p2p/config.rs @@ -0,0 +1,17 @@ +use super::libp2p_core::Multiaddr; + +pub struct NetworkConfig { + pub config_dir: String, + pub listen_multiaddr: Multiaddr, +} + +impl NetworkConfig { + pub fn default() -> Self{ + Self { + config_dir: ".lighthouse".to_string(), + listen_multiaddr: "/ip4/0.0.0.0/tcp/0" + .parse::().unwrap() + + } + } +} diff --git a/src/p2p/floodsub.rs b/src/p2p/floodsub.rs index 3bc14ab70..f48f2cfa5 100644 --- a/src/p2p/floodsub.rs +++ b/src/p2p/floodsub.rs @@ -1,6 +1,7 @@ extern crate bigint; extern crate bytes; extern crate futures; +extern crate hex; extern crate libp2p_peerstore; extern crate libp2p_identify; extern crate libp2p_core; @@ -14,9 +15,9 @@ extern crate tokio_io; extern crate tokio_timer; extern crate tokio_stdin; +use super::state::NetworkState; use self::bigint::U512; use self::futures::{ Future, Stream }; -use self::libp2p_peerstore::PeerId; use self::libp2p_core::{ AddrComponent, Endpoint, Multiaddr, Transport, ConnectionUpgrade }; use self::libp2p_floodsub::{ FloodSubUpgrade, FloodSubFuture }; use self::libp2p_kad::{ KademliaUpgrade, KademliaProcessingFuture}; @@ -26,16 +27,14 @@ use std::sync::{ Arc, RwLock }; use std::time::{ Duration, Instant }; use std::ops::Deref; use std::io::Error as IoError; -use libp2p_peerstore::memory_peerstore::MemoryPeerstore; use self::tokio_io::{ AsyncRead, AsyncWrite }; use self::bytes::Bytes; -pub fn listen(peer_id: PeerId, - peer_store: Arc, - log: &Logger) +pub fn listen(state: NetworkState, log: &Logger) { - let listen_multiaddr: Multiaddr = "/ip4/0.0.0.0/tcp/0" - .parse::().expect("Failed to parse listen multiaddr."); + let peer_store = state.peer_store; + let peer_id = state.peer_id; + let listen_multiaddr = state.listen_multiaddr; info!(log, "Local PeerId: {:?}", peer_id); diff --git a/src/p2p/keys.rs b/src/p2p/keys.rs index 300c03bf7..61d7f524a 100644 --- a/src/p2p/keys.rs +++ b/src/p2p/keys.rs @@ -8,6 +8,9 @@ use std::io::prelude::*; use std::fs::File; use slog::Logger; +use std::io::Error as IoError; +use std::path::Path; +use super::config::NetworkConfig; use self::secp256k1::key::{ SecretKey, PublicKey }; use self::libp2p_peerstore::PeerId; @@ -15,16 +18,13 @@ const LOCAL_PK_FILE: &str = "local.pk"; const LOCAL_SK_FILE: &str = "local.sk"; const BOOTSTRAP_PK_FILE: &str = "bootstrap.pk"; -pub fn peer_id_from_pub_key(pk: &PublicKey) -> PeerId { - let curve = get_curve(); - PeerId::from_public_key(&pk.serialize_vec(&curve, false)) -} - fn get_curve() -> secp256k1::Secp256k1 { secp256k1::Secp256k1::new() } /// Generates a new public and secret key pair and writes them to /// individual files. -pub fn generate_keys(log: &Logger) -> std::io::Result<()> { +pub fn generate_keys(config: NetworkConfig, log: &Logger) + -> Result<(), IoError> +{ info!(log, "Generating keys..."); let mut rng = rand::thread_rng(); let curve = get_curve(); @@ -42,32 +42,3 @@ pub fn generate_keys(log: &Logger) -> std::io::Result<()> { s_file.write(s_string.as_bytes())?; Ok(()) } - -pub fn load_bootstrap_pk(log: &Logger) -> PublicKey { - info!(log, "Loading boostrap public key from filesystem..."); - load_pk_from_file(BOOTSTRAP_PK_FILE) -} - -pub fn load_local_keys(log: &Logger) -> (PublicKey, SecretKey) { - info!(log, "Loading local keys from filesystem..."); - (load_pk_from_file(LOCAL_PK_FILE), load_sk_from_file(LOCAL_SK_FILE)) -} - -fn load_sk_from_file(file: &str) -> SecretKey { - let vec = load_vec_from_hex_file(file); - let curve = get_curve(); - SecretKey::from_slice(&curve, &vec).expect("secret key invalid") -} - -fn load_pk_from_file(file: &str) -> PublicKey { - let vec = load_vec_from_hex_file(file); - let curve = get_curve(); - PublicKey::from_slice(&curve, &vec).expect("public key invalid") -} - -fn load_vec_from_hex_file(file: &str) -> Vec { - let mut contents = String::new(); - let mut file = File::open(file).expect("key not found"); - file.read_to_string(&mut contents).expect("error reading from file"); - hex::decode(contents).expect("public key corrupt") -} diff --git a/src/p2p/mod.rs b/src/p2p/mod.rs index 2626c73a4..f483b87a1 100644 --- a/src/p2p/mod.rs +++ b/src/p2p/mod.rs @@ -1,2 +1,9 @@ +extern crate hex; +extern crate libp2p_core; +extern crate libp2p_peerstore; +extern crate secp256k1; + pub mod floodsub; -pub mod keys; +pub mod state; +// pub mod keys; +pub mod config; diff --git a/src/p2p/state.rs b/src/p2p/state.rs new file mode 100644 index 000000000..787bac396 --- /dev/null +++ b/src/p2p/state.rs @@ -0,0 +1,55 @@ +use std::io::Read; +use std::error::Error; +use std::path::Path; +use std::fs::File; +use std::sync::Arc; + +use super::hex; +use super::secp256k1::Secp256k1; +use super::secp256k1::key::{ SecretKey, PublicKey }; +use super::libp2p_core::Multiaddr; +use super::libp2p_peerstore::PeerId; +use super::libp2p_peerstore::json_peerstore::JsonPeerstore; +use super::config::NetworkConfig; + + +const PEERS_FILE: &str = "peerstore.json"; +const LOCAL_SK_FILE: &str = "local.sk"; + +pub struct NetworkState { + pub pubkey: PublicKey, + pub seckey: SecretKey, + pub peer_id: PeerId, + pub listen_multiaddr: Multiaddr, + pub peer_store: Arc, +} + +impl NetworkState { + pub fn new(config: &NetworkConfig) -> Result > { + let curve = Secp256k1::new(); + let seckey = { + let path = Path::new(&config.config_dir).join(LOCAL_SK_FILE); + let mut contents = String::new(); + let mut file = File::open(path)?; + file.read_to_string(&mut contents)?; + let vec = hex::decode(contents)?; + SecretKey::from_slice(&curve, &vec)? + }; + let pubkey = PublicKey::from_secret_key(&curve, &seckey)?; + let peer_id = PeerId::from_public_key( + &pubkey.serialize_vec(&curve, false)); + let peer_store = { + let path = Path::new(&config.config_dir).join(PEERS_FILE); + let base = JsonPeerstore::new(path)?; + Arc::new(base) + }; + let listen_multiaddr = "/ip4/0.0.0.0/tcp/0".parse::()?; + Ok(Self { + seckey, + pubkey, + peer_id, + listen_multiaddr, + peer_store, + }) + } +}