Browse Source

Wrote TestInterface

interface-2
Lev 3 years ago
parent
commit
2a7a97f592
  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_cbor",
"sha2",
"spin 0.9.2",
]
[[package]]
@ -245,7 +246,7 @@ version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
dependencies = [
"spin",
"spin 0.5.2",
]
[[package]]
@ -260,6 +261,15 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
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]]
name = "memoffset"
version = "0.6.4"
@ -557,6 +567,15 @@ version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
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]]
name = "spki"
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 }
core-error = "0.0.1-rc4"
serde_cbor = "0.11.2"
spin = "0.9.2"
[profile.dev.package.num-bigint-dig]
opt-level = 3

1
examples/test_ip_connection.rs

@ -15,6 +15,7 @@ fn main() {
test();
}
#[cfg(feature = "std")]
fn test() -> IFResult<()> {
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::message::MessageBytes;
use crate::res::IFResult;
use alloc::string::String;
use alloc::vec::Vec;
use alloc::vec;
use alloc::string::ToString;
use alloc::sync::Arc;
use spin::Mutex;
#[derive(Default)]
pub struct TestInterface {
pub struct SimpleTestInterface {
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<()> {
Ok(())
}
@ -76,4 +81,60 @@ pub mod test_interface {
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::Vec;
use alloc::string::{String, ToString};
use core::cmp::min;
use core::ops::RangeInclusive;
use core::str::from_utf8;
use core::time::Duration;
use crate::interface::{Interface, InterfaceRequirements, TargetingData};
use crate::interfaces::ip::MessageType::PeerRequest;
use crate::message::MessageBytes;
use crate::res::{IFError, IFResult};
use crate::res::IFError::General;
@ -74,7 +71,7 @@ impl Interface for IPInterface {
println!("New client: {:?}", addr);
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");
@ -87,7 +84,7 @@ impl Interface for IPInterface {
let mut message_take = connection.take(size as u64);
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};
self.package_queue.push(package);
@ -134,7 +131,7 @@ impl Interface for IPInterface {
package_type: MessageType::Common,
size: message.len() as u32,
message: Vec::from(message),
});
})?;
println!("Sent message");
Ok(())
}
@ -148,7 +145,7 @@ impl Interface for IPInterface {
impl IPInterface {
pub fn new() -> IFResult<Self> {
let mut listener = match create_tcp_listener() {
let listener = match create_tcp_listener() {
Some(listener) => listener,
None => {
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 {
match net::TcpListener::bind("127.0.0.1:".to_owned() + &port.to_string()) {
Ok(listener) => return Some(listener),
Err(e) => {}
Err(_e) => {}
}
};
None
@ -235,20 +232,19 @@ fn test_creating_connection() -> IFResult<()> {
let mut interface2 = IPInterface::new()?;
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
});
thread::sleep(Duration::from_millis(10));
let t2 = std::thread::spawn(move || {
interface2.main_loop_iteration();
interface2.main_loop_iteration().unwrap();
interface2
});
let res1 = t1.join();
match res1 {
Ok(mut res) => {
Ok(_res) => {
println!("Thread Ok");
}
Err(e) => println!("{:?}", e)
}
@ -258,7 +254,7 @@ fn test_creating_connection() -> IFResult<()> {
println!("Thread Ok");
match res.receive() {
Ok(tmp) => match tmp {
Some((message, metadata)) => println!("Received {:?}", message),
Some((message, _metadata)) => println!("Received {:?}", message),
None => println!("None")
}
Err(e) => println!("{:?}", e)

1
src/lib.rs

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

3
src/message.rs

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

8
src/transport.rs

@ -147,11 +147,11 @@ impl Transport {
}
#[cfg(test)]
use crate::interface::test_interface::TestInterface;
use crate::interface::test_interface::SimpleTestInterface;
#[test]
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());
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());
@ -166,7 +166,7 @@ fn test_adding_peer_to_transport() {
#[test]
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 peer_id = transport.find_or_add_peer(interface_id.clone(), interface_targeting_data.clone());
transport.send_message(vec![239, 123], None).unwrap();
@ -178,7 +178,7 @@ fn test_transport_sending() {
#[test]
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 peer_id = transport.find_or_add_peer(interface_id.clone(), interface_targeting_data.clone());
transport.send_message(vec![239, 123], None).unwrap();

Loading…
Cancel
Save