src: move network types to new file

This commit is contained in:
Ujjwal Sharma 2021-03-31 12:31:29 +05:30
parent 4b2a20c581
commit 53bd1c9e6c
Signed by untrusted user: ryzokuken
GPG Key ID: 460B292812C67D9F
2 changed files with 66 additions and 59 deletions

View File

@ -1,70 +1,17 @@
use async_std::fs;
use async_std::net::{IpAddr, UdpSocket};
use async_std::net::UdpSocket;
use async_std::path::PathBuf;
use clap::{load_yaml, App};
use ed25519_dalek::{Keypair, PublicKey};
use ed25519_dalek::Keypair;
mod keypair;
use keypair::{SSBKeypair, SSBPublicKey};
use keypair::SSBKeypair;
mod network;
use network::Node;
type Config = toml::map::Map<String, toml::Value>;
enum Protocol {
Net,
Ws,
Wss,
}
struct Node {
protocol: Protocol,
host: IpAddr,
port: u16,
pubkey: PublicKey,
}
impl Node {
fn to_base64(&self) -> String {
let proto = match self.protocol {
Protocol::Net => "net",
Protocol::Ws => "ws",
Protocol::Wss => "wss",
};
format!(
"{}:{}:{}~shs:{}",
proto,
self.host,
self.port,
self.pubkey.to_base64()
)
}
fn from_base64(packet: &str) -> Self {
let mut packet = packet.splitn(4, ':');
let protocol = match packet.next().unwrap() {
"net" => Protocol::Net,
"ws" => Protocol::Ws,
"wss" => Protocol::Wss,
_ => panic!("unknown protocol"),
};
let host = IpAddr::V4(packet.next().unwrap().parse().unwrap());
let port = packet
.next()
.unwrap()
.splitn(2, '~')
.next()
.unwrap()
.parse()
.unwrap();
let pubkey = SSBPublicKey::from_base64(packet.next().unwrap());
Node {
protocol,
host,
port,
pubkey,
}
}
}
#[async_std::main]
async fn main() {
let options = load_yaml!("options.yaml");

60
src/network.rs Normal file
View File

@ -0,0 +1,60 @@
use async_std::net::IpAddr;
use ed25519_dalek::PublicKey;
use crate::keypair::SSBPublicKey;
enum Protocol {
Net,
Ws,
Wss,
}
pub struct Node {
protocol: Protocol,
host: IpAddr,
port: u16,
pubkey: PublicKey,
}
impl Node {
pub fn to_base64(&self) -> String {
let proto = match self.protocol {
Protocol::Net => "net",
Protocol::Ws => "ws",
Protocol::Wss => "wss",
};
format!(
"{}:{}:{}~shs:{}",
proto,
self.host,
self.port,
self.pubkey.to_base64()
)
}
pub fn from_base64(packet: &str) -> Self {
let mut packet = packet.splitn(4, ':');
let protocol = match packet.next().unwrap() {
"net" => Protocol::Net,
"ws" => Protocol::Ws,
"wss" => Protocol::Wss,
_ => panic!("unknown protocol"),
};
let host = IpAddr::V4(packet.next().unwrap().parse().unwrap());
let port = packet
.next()
.unwrap()
.splitn(2, '~')
.next()
.unwrap()
.parse()
.unwrap();
let pubkey = SSBPublicKey::from_base64(packet.next().unwrap());
Node {
protocol,
host,
port,
pubkey,
}
}
}