Browse Source

Wrote TestInterface

master
Lev 3 years ago
parent
commit
362102c7dc
  1. 21
      Cargo.lock
  2. 1
      Cargo.toml
  3. 1
      examples/test_ip_connection.rs
  4. 67
      src/interface.rs
  5. 22
      src/interfaces/ip.rs
  6. 1
      src/lib.rs
  7. 3
      src/message.rs
  8. 8
      src/transport.rs

21
Cargo.lock generated

@ -237,6 +237,7 @@ dependencies = [
"serde", "serde",
"serde_cbor", "serde_cbor",
"sha2", "sha2",
"spin 0.9.2",
] ]
[[package]] [[package]]
@ -245,7 +246,7 @@ version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
dependencies = [ dependencies = [
"spin", "spin 0.5.2",
] ]
[[package]] [[package]]
@ -260,6 +261,15 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c7d73b3f436185384286bd8098d17ec07c9a7d2388a6599f824d8502b529702a" checksum = "c7d73b3f436185384286bd8098d17ec07c9a7d2388a6599f824d8502b529702a"
[[package]]
name = "lock_api"
version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712a4d093c9976e24e7dbca41db895dabcbac38eb5f4045393d17a95bdfb1109"
dependencies = [
"scopeguard",
]
[[package]] [[package]]
name = "memoffset" name = "memoffset"
version = "0.6.4" version = "0.6.4"
@ -557,6 +567,15 @@ version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d"
[[package]]
name = "spin"
version = "0.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "511254be0c5bcf062b019a6c89c01a664aa359ded62f78aa72c6fc137c0590e5"
dependencies = [
"lock_api",
]
[[package]] [[package]]
name = "spki" name = "spki"
version = "0.4.1" version = "0.4.1"

1
Cargo.toml

@ -20,6 +20,7 @@ serde = { version = "1.0", features = ["derive", "alloc"], default-features = fa
rayon = { version = "1.5.1", optional = true } rayon = { version = "1.5.1", optional = true }
core-error = "0.0.1-rc4" core-error = "0.0.1-rc4"
serde_cbor = "0.11.2" serde_cbor = "0.11.2"
spin = "0.9.2"
[profile.dev.package.num-bigint-dig] [profile.dev.package.num-bigint-dig]
opt-level = 3 opt-level = 3

1
examples/test_ip_connection.rs

@ -15,6 +15,7 @@ fn main() {
test(); test();
} }
#[cfg(feature = "std")]
fn test() -> IFResult<()> { fn test() -> IFResult<()> {
let message = *b"Hello world from iron forest"; let message = *b"Hello world from iron forest";

67
src/interface.rs

@ -48,16 +48,21 @@ pub mod test_interface {
use crate::interface::{Interface, InterfaceRequirements, TargetingData}; use crate::interface::{Interface, InterfaceRequirements, TargetingData};
use crate::message::MessageBytes; use crate::message::MessageBytes;
use crate::res::IFResult; use crate::res::IFResult;
use alloc::string::String;
use alloc::vec::Vec; use alloc::vec::Vec;
use alloc::vec;
use alloc::string::ToString;
use alloc::sync::Arc;
use spin::Mutex;
#[derive(Default)] #[derive(Default)]
pub struct TestInterface { pub struct SimpleTestInterface {
messages: Vec<(Vec<u8>, TargetingData)>, messages: Vec<(Vec<u8>, TargetingData)>,
} }
impl InterfaceRequirements for TestInterface {} impl InterfaceRequirements for SimpleTestInterface {}
impl Interface for TestInterface { impl Interface for SimpleTestInterface {
fn main_loop_iteration(&mut self) -> IFResult<()> { fn main_loop_iteration(&mut self) -> IFResult<()> {
Ok(()) Ok(())
} }
@ -76,4 +81,60 @@ pub mod test_interface {
Ok(self.messages.pop()) Ok(self.messages.pop())
} }
} }
pub type Storage = Vec<(Vec<u8>, TargetingData)>;
#[derive(Default)]
pub struct TestInterface {
this_peer_id: String,
storage: Arc<Mutex<Storage>>,
messages: Vec<(Vec<u8>, TargetingData)>,
}
impl Interface for TestInterface {
fn main_loop_iteration(&mut self) -> IFResult<()> {
let mut storage_locked = self.storage.lock();
while let Some(i) = storage_locked
.iter()
.position(|msg| msg.1 == self.this_peer_id)
{
self.messages.push(storage_locked.remove(i));
}
Ok(())
}
fn id(&self) -> &str {
"test_interface"
}
fn send(&mut self, message: &[u8], target: Option<TargetingData>) -> IFResult<()> {
Ok(self
.storage
.lock()
.push((Vec::from(message), target.unwrap_or_default())))
}
fn receive(&mut self) -> IFResult<Option<(MessageBytes, TargetingData)>> {
Ok(self.messages.pop())
}
}
impl InterfaceRequirements for TestInterface {}
pub fn create_test_interfaces(n: usize) -> Vec<TestInterface> {
let storage_mutex = Arc::new(Mutex::new(vec![]));
(0..n).map(|i| TestInterface {
this_peer_id: i.to_string(),
storage: storage_mutex.clone(),
messages: vec![],
}).collect()
}
#[test]
fn test_test_interface() {
let mut interfaces = create_test_interfaces(2);
interfaces[0].send(b"123", Some("1".to_string())).unwrap();
interfaces[1].main_loop_iteration().unwrap();
assert_eq!(interfaces[1].receive().unwrap().unwrap().0.as_slice(), b"123");
}
} }

22
src/interfaces/ip.rs

@ -4,13 +4,10 @@ use std::thread;
use alloc::vec; use alloc::vec;
use alloc::vec::Vec; use alloc::vec::Vec;
use alloc::string::{String, ToString}; use alloc::string::{String, ToString};
use core::cmp::min;
use core::ops::RangeInclusive; use core::ops::RangeInclusive;
use core::str::from_utf8;
use core::time::Duration; use core::time::Duration;
use crate::interface::{Interface, InterfaceRequirements, TargetingData}; use crate::interface::{Interface, InterfaceRequirements, TargetingData};
use crate::interfaces::ip::MessageType::PeerRequest;
use crate::message::MessageBytes; use crate::message::MessageBytes;
use crate::res::{IFError, IFResult}; use crate::res::{IFError, IFResult};
use crate::res::IFError::General; use crate::res::IFError::General;
@ -74,7 +71,7 @@ impl Interface for IPInterface {
println!("New client: {:?}", addr); println!("New client: {:?}", addr);
self.connections.push(stream) self.connections.push(stream)
} }
Err(e) => return Err(IFError::General(String::from("No incoming connection"))), Err(_e) => return Err(IFError::General(String::from("No incoming connection"))),
} }
println!("Hello from mainloop"); println!("Hello from mainloop");
@ -87,7 +84,7 @@ impl Interface for IPInterface {
let mut message_take = connection.take(size as u64); let mut message_take = connection.take(size as u64);
let mut message: Vec<u8> = vec![]; let mut message: Vec<u8> = vec![];
message_take.read_to_end(&mut message); message_take.read_to_end(&mut message)?;
let package = IPPackage {version, package_type, size, message}; let package = IPPackage {version, package_type, size, message};
self.package_queue.push(package); self.package_queue.push(package);
@ -134,7 +131,7 @@ impl Interface for IPInterface {
package_type: MessageType::Common, package_type: MessageType::Common,
size: message.len() as u32, size: message.len() as u32,
message: Vec::from(message), message: Vec::from(message),
}); })?;
println!("Sent message"); println!("Sent message");
Ok(()) Ok(())
} }
@ -148,7 +145,7 @@ impl Interface for IPInterface {
impl IPInterface { impl IPInterface {
pub fn new() -> IFResult<Self> { pub fn new() -> IFResult<Self> {
let mut listener = match create_tcp_listener() { let listener = match create_tcp_listener() {
Some(listener) => listener, Some(listener) => listener,
None => { None => {
return Err(IFError::General(String::from("Unable to open TCP listener"))); return Err(IFError::General(String::from("Unable to open TCP listener")));
@ -194,7 +191,7 @@ fn create_tcp_listener() -> Option<net::TcpListener> {
for port in SOCKET_RANGE { for port in SOCKET_RANGE {
match net::TcpListener::bind("127.0.0.1:".to_owned() + &port.to_string()) { match net::TcpListener::bind("127.0.0.1:".to_owned() + &port.to_string()) {
Ok(listener) => return Some(listener), Ok(listener) => return Some(listener),
Err(e) => {} Err(_e) => {}
} }
}; };
None None
@ -235,20 +232,19 @@ fn test_creating_connection() -> IFResult<()> {
let mut interface2 = IPInterface::new()?; let mut interface2 = IPInterface::new()?;
let t1 = std::thread::spawn(move || { let t1 = std::thread::spawn(move || {
interface1.send(&message, Some(String::from("127.0.0.1:50001"))); interface1.send(&message, Some(String::from("127.0.0.1:50001"))).unwrap();
interface1 interface1
}); });
thread::sleep(Duration::from_millis(10)); thread::sleep(Duration::from_millis(10));
let t2 = std::thread::spawn(move || { let t2 = std::thread::spawn(move || {
interface2.main_loop_iteration(); interface2.main_loop_iteration().unwrap();
interface2 interface2
}); });
let res1 = t1.join(); let res1 = t1.join();
match res1 { match res1 {
Ok(mut res) => { Ok(_res) => {
println!("Thread Ok"); println!("Thread Ok");
} }
Err(e) => println!("{:?}", e) Err(e) => println!("{:?}", e)
} }
@ -258,7 +254,7 @@ fn test_creating_connection() -> IFResult<()> {
println!("Thread Ok"); println!("Thread Ok");
match res.receive() { match res.receive() {
Ok(tmp) => match tmp { Ok(tmp) => match tmp {
Some((message, metadata)) => println!("Received {:?}", message), Some((message, _metadata)) => println!("Received {:?}", message),
None => println!("None") None => println!("None")
} }
Err(e) => println!("{:?}", e) Err(e) => println!("{:?}", e)

1
src/lib.rs

@ -10,6 +10,7 @@ extern crate rand;
extern crate rsa; extern crate rsa;
extern crate serde; extern crate serde;
extern crate core_error; extern crate core_error;
extern crate spin;
mod crypto; mod crypto;
mod ironforce; mod ironforce;

3
src/message.rs

@ -338,9 +338,6 @@ impl MessageBuilder {
#[cfg(test)] #[cfg(test)]
use alloc::vec; use alloc::vec;
#[cfg(feature = "std")]
#[cfg(test)]
use std::println;
#[test] #[test]
fn test_hashing_message_type() { fn test_hashing_message_type() {

8
src/transport.rs

@ -147,11 +147,11 @@ impl Transport {
} }
#[cfg(test)] #[cfg(test)]
use crate::interface::test_interface::TestInterface; use crate::interface::test_interface::SimpleTestInterface;
#[test] #[test]
fn test_adding_peer_to_transport() { fn test_adding_peer_to_transport() {
let mut transport = Transport::new(vec![Box::new(TestInterface::default())]); let mut transport = Transport::new(vec![Box::new(SimpleTestInterface::default())]);
let (interface_id, interface_targeting_data) = ("test_interface".to_string(), "hi".to_string()); let (interface_id, interface_targeting_data) = ("test_interface".to_string(), "hi".to_string());
assert!(transport.get_peer_by_parameters(interface_id.as_str(), interface_targeting_data.as_str()).is_none()); assert!(transport.get_peer_by_parameters(interface_id.as_str(), interface_targeting_data.as_str()).is_none());
let peer_id = transport.find_or_add_peer(interface_id.clone(), interface_targeting_data.clone()); let peer_id = transport.find_or_add_peer(interface_id.clone(), interface_targeting_data.clone());
@ -166,7 +166,7 @@ fn test_adding_peer_to_transport() {
#[test] #[test]
fn test_transport_sending() { fn test_transport_sending() {
let mut transport = Transport::new(vec![Box::new(TestInterface::default())]); let mut transport = Transport::new(vec![Box::new(SimpleTestInterface::default())]);
let (interface_id, interface_targeting_data) = ("test_interface".to_string(), "hi".to_string()); let (interface_id, interface_targeting_data) = ("test_interface".to_string(), "hi".to_string());
let peer_id = transport.find_or_add_peer(interface_id.clone(), interface_targeting_data.clone()); let peer_id = transport.find_or_add_peer(interface_id.clone(), interface_targeting_data.clone());
transport.send_message(vec![239, 123], None).unwrap(); transport.send_message(vec![239, 123], None).unwrap();
@ -178,7 +178,7 @@ fn test_transport_sending() {
#[test] #[test]
fn test_transport_receiving() { fn test_transport_receiving() {
let mut transport = Transport::new(vec![Box::new(TestInterface::default())]); let mut transport = Transport::new(vec![Box::new(SimpleTestInterface::default())]);
let (interface_id, interface_targeting_data) = ("test_interface".to_string(), "hi".to_string()); let (interface_id, interface_targeting_data) = ("test_interface".to_string(), "hi".to_string());
let peer_id = transport.find_or_add_peer(interface_id.clone(), interface_targeting_data.clone()); let peer_id = transport.find_or_add_peer(interface_id.clone(), interface_targeting_data.clone());
transport.send_message(vec![239, 123], None).unwrap(); transport.send_message(vec![239, 123], None).unwrap();

Loading…
Cancel
Save